如何使用jsoncpp将特定值保存到txt列表中?
我有yahoo finance json文件,我希望从quote
列表中分离日期,关闭和音量,并使用逗号分隔符将其保存在单个文本文件中。这是我的json脚本。如何使用jsoncpp将特定值保存到txt列表中?
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse(YahooJson, root);
if(not parsingSuccessful)
{
// Report failures and their locations
// in the document.
std::cout<<"Failed to parse JSON"<<std::endl
<<reader.getFormatedErrorMessages()
<<std::endl;
return 1;
}else{
std::cout<<"\nSucess parsing json\n"<<std::endl;
std::cout << root<< std::endl;
std::cout <<"No of Days = "<< root["query"]["count"].asInt() << std::endl;
//below for loop returns an error
for (auto itr : root["query"]["result"]["quote"]) {
std::string val = itr.asString();
}
}
我能够获取的JSON值来赢得成功并打印root["query"]["count"].asInt()
但是当我去到列表中的值(quote
)我不知道如何通过循环引用(查询 - > result->报价)获得日期,关闭和音量值?
编辑
也试过这个方法
const Json::Value& quotes = root["query"]["results"]["quote"];
for (int i = 0; i < quotes.size(); i++){
std::cout << " Date: " << quotes[i]["Date"].asString();
std::cout << " Close: " << quotes[i]["Close"].asFloat();
std::cout << " Volume: " << quotes[i]["Volume"].asFloat();
std::cout << std::endl;
}
它的工作原理,只有当输出为日期。对于关闭和音量输出其与运行时错误消息,并且也是这个错误
what() type is not convertible to string
您还没有指定您正在使用的JSON库退出,我不知道雅虎的财务数据不够好,要知道确切的字段名称,但如果您使用的是JsonCpp库,里面有文档here,并且您询问如何遍历一个JSON数组,然后使用迭代器会是这个样子
const Json::Value quote = root["query"]["results"]["quote"];
for (Json::ValueConstIterator itr = quote.begin(); itr != quote.end(); ++itr)
{
const Json::Value date = (*itr)["Date"];
const Json::Value close = (*itr)["Close"];
const Json::Value volume = (*itr)["Volume"];
std::cout << "Date: " << date.asString() << std::endl;
std::cout << "Close: " << close.asString() << std::endl;
std::cout << "Volume: " << volume.asString() << std::endl;
}
谢谢代码后,小修正也没有显示任何结果Json :: Value quote = root [“query”] [“result”] [“quote”]; (Json :: ValueIterator itr = quote.begin(); itr!= quote.end(); itr ++) { Json :: Value date =(* itr)[“Date”]; Json :: Value close =(* itr)[“Close”]; Json :: Value volume =(* itr)[“Volume”]; std :: cout Eka
我以前没有编译过代码,但是我由于你的评论去编译它的工作。现在的答案显示了我用JsonCpp代码编译和测试的代码以及您提供的yahoo finance json链接中显示的数据。 –
做到这一点的一种方式你能澄清你正在使用哪个JSON库吗?你定义'Json :: Value'和'Json :: Reader'的导入库是什么?如果你发布了一段你试图访问的JSON记录的代码片段,这也可以帮助你清楚它是否是一个JSON数组或其他东西。 –
当我尝试你编辑的第二种方法时,我得到'what():Value不能转换为float.'这很有意义,因为Close和Volume的数据在链接的示例JSON数据中以字符串而不是数字文字表示。有四舍五入的原因,你可能更喜欢用不同的方式解析它。如果双打没问题,您应该可以使用scanf或字符串流将其从字符串转换。 –