我有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庫嗎?你定義'Json :: Value'和'Json :: Reader'的導入庫是什麼?如果你發佈了一段你試圖訪問的JSON記錄的代碼片段,這也可以幫助你清楚它是否是一個JSON數組或其他東西。 –
當我嘗試你編輯的第二種方法時,我得到'what():Value不能轉換爲float.'這很有意義,因爲Close和Volume的數據在鏈接的示例JSON數據中以字符串而不是數字文字表示。有四捨五入的原因,你可能更喜歡用不同的方式解析它。如果雙打沒問題,您應該可以使用scanf或字符串流將其從字符串轉換。 –