2012-03-02 56 views
3

解析YouTube數據下面是一個例子飼料,我想解析: https://gdata.youtube.com/feeds/api/users/aniBOOM/subscriptions?v=2&alt=json使用C++和Jsoncpp

你可以用http://json.parser.online.fr/檢查,看看它包含的內容。

解析youtube提供的數據Feed時,我遇到了一個小問題。第一個問題是YouTube提供的數據包裹在飼料領域的方式,因爲我不能直接從原始json文件解析用戶名,所以我不得不解析第一個輸入字段,並從中生成新的Json數據。

但無論如何,問題是,由於某種原因,不包括除第一用戶名更多,我不知道爲什麼,因爲如果你檢查網絡解析器,飼料條目應該包含所有的用戶名。

`

 data = value["feed"]["entry"]; 
     Json::StyledWriter writer; 
     std::string outputConfig = writer.write(data); 
//This removes [ at the beginning of entry and also last ] so we can treat it as a Json data 
     size_t found; 
     found=outputConfig.find_first_of("["); 
     int sSize = outputConfig.size();    
     outputConfig.erase(0,1); 
     outputConfig.erase((sSize-1),sSize); 

     reader.parse(outputConfig, value2, false); 

     cout << value2 << endl; 

     Json::Value temp; 
     temp = value2["yt$username"]["yt$display"]; 
     cout << temp << endl; 

     std::string username = writer.write(temp); 
     int sSize2 = username.size();   
     username.erase(0,1); 
     username.erase((sSize2-3),sSize2); 

` 但出於某種原因[]也解決削減我生成的數據,如果我打印出來的數據不刪除[]我可以看到所有的用戶,但在這種情況下,我無法提取temp = value2 [「yt $ username」] [「yt $ display」];

回答

3

在JSON,中括號代表陣列(很好的參考here)。您可以在聯機解析器中看到這一點 - 對象(帶有一個或多個鍵/值對{"key1": "value1", "key2": "value2"})的項用藍色+/-符號表示,陣列(用逗號[{arrayItem1}, {arrayItem2}, {arrayItem3}]分隔的括號內的項)用紅色/ - 標誌。

由於條目是一個數組,你應該能夠做這樣的事情通過他們迭代:

// Assumes value is a Json::Value 
Json::Value entries = value["feed"]["entry"]; 

size_t size = entries.size(); 
for (size_t index=0; index<size; ++index) { 
    Json::Value entryNode = entries[index]; 
    cout << entryNode["yt$username"]["yt$display"].asString() << endl; 
} 
+0

是的,我不知道能不能被視爲一個陣列...你舉的例子完全解決我的問題。非常感謝! – Mare 2012-03-22 19:03:30