2016-07-23 91 views
0

我有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 
+0

做到這一點的一種方式你能澄清你正在使用哪個JSON庫嗎?你定義'Json :: Value'和'Json :: Reader'的導入庫是什麼?如果你發佈了一段你試圖訪問的JSON記錄的代碼片段,這也可以幫助你清楚它是否是一個JSON數組或其他東西。 –

+1

當我嘗試你編輯的第二種方法時,我得到'what():Value不能轉換爲float.'這很有意義,因爲Close和Volume的數據在鏈接的示例JSON數據中以字符串而不是數字文字表示。有四捨五入的原因,你可能更喜歡用不同的方式解析它。如果雙打沒問題,您應該可以使用scanf或字符串流將其從字符串轉換。 –

回答

1

您還沒有指定您正在使用的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; 
} 
+0

謝謝代碼後,小修正也沒有顯示任何結果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 <<「\ nDate \ n」<< date.asString()<< std :: endl; } ' – Eka

+0

我以前沒有編譯過代碼,但是我由於你的評論去編譯它的工作。現在的答案顯示了我用JsonCpp代碼編譯和測試的代碼以及您提供的yahoo finance json鏈接中顯示的數據。 –

相關問題