JSON(JavaScript Object Notation)是一種輕量級的資料交換語言,以文字為基礎,且易於讓人閱讀。儘管JSON是Javascript的一個子集,但JSON是獨立於語言的文字格式,並且採用了類似於C語言家族的一些習慣。
不過目前C++並無內建函式可以解析JSON (Parse JSON),於是我便到GitHub找輕便好用的套件:JSON for Modern C++
上圖展示套件有四種方式來讀取JSON資料,因為我是要從檔案讀取來解析,所以足夠我使用囉~
接續上一篇文章:讀取整個檔案為字串 (Read Whole File to String),接著我們要將它解析JSON (Parse JSON)。
JSON格式看起來挺工整,可以清楚知道如何取得我們想要的值。儘管可以自己寫一個解析器(Parser),然而我們卻沒有時間去開發和除錯,所以還是直接取用先人的貢獻,然後我們可以專注在產品核心上!
/** Theme: Parse JSON IDE: Xcode 7 Language: C++ Date: 105/04/04 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ #include <iostream> #include <fstream> #include "json.hpp" using namespace cv; using namespace std; using json = nlohmann::json; int main(int argc, char** argv) { ifstream inFile; inFile.open("HappyFace.json");// Open the input file stringstream strStream; strStream << inFile.rdbuf();// Read the file string string = strStream.str();// string holds the content of the file // cout << string << endl;// You can do anything with the string json happyJson = json::parse(string); cout << happyJson["face"][0]["attribute"]["age"] << endl; return 0; }
編譯執行後列印:
{“range":5,"value":29}
這些值代表年紀為29正負5歲,我是用林志玲的相片唷:P~
參考:
Comments on: "[C++] 解析JSON (Parse JSON)" (2)
為什麼 " 要寫成 " ,<要寫成 <,>要寫成 >
讚讚
啊哈~感謝你的回報,因為部落格平台發文時編碼有問題,就你所講的要顯示"才對! 😀
讚讚