我有yahoo finance json文件,要从quote
列表中隔离Date,Close和volume,并用逗号分隔的相同顺序将其保存在单个文本文件中。这是我的json脚本。
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()
但是当我转到列表values(quote
)时,我不知道如何遍历引用(query-> result-> quote)以获取Date,close和volume值?
编辑
也尝试过这种方法
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;
}
它仅在输出为Date时有效。对于关闭和体积输出,它会退出并显示运行时错误消息以及此错误
what() type is not convertible to string
您尚未指定要使用的JSON库,并且我对Yahoo财务数据的了解还不够,无法知道确切的字段名称,但是如果您使用的是JsonCpp库,该库在此处提供了文档,并且您正在询问如何在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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句