# json ## 介紹 json是一種文件格式,全稱JavaScript Object Notation,它是來自 JavaScript,能夠給人閱讀的文本,通常用來作為傳輸數據的數據格式。 在程式中通常以object, record, struct, dictionary, hash table, keyed list, associative array表示 ## 格式 以 { "左大括號" 開始,以 } "右大括號" 結束 每個名稱後都有 : "冒號" 每個名稱/值都用 , "逗號" 分隔 ### 例子 ``` { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 27, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [], "spouse": null } ``` 為了更容易閱讀json,所以可以把它用樹表示 ### 例子 ![](https://i.imgur.com/SRRjZSu.png) # json-c ## 安裝方法 ``` sudo apt install libjson-c-dev ``` ## 終端機 編譯 ``` gcc "fileName".c -ljson-c -o "fileName" ``` 執行 ``` ./"fileName" ``` ## visual studio code 開啟tasks.json 在args新增"-l"和"json-c" ``` { "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc-9 建置使用中檔案", "command": "/usr/bin/gcc-9", "args": [ "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}", "-l", "json-c" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "偵錯工具產生的工作。" } ], "version": "2.0.0" } ``` ## 語法 讀取json return 如果讀取文件失敗,則此函數返回 NULL ``` json_object *root = json_object_from_file(""fileName".json"); ``` 用一行印出整個json ``` printf("The json file:\n\n%s\n", json_object_to_json_string(root)); ``` 格式化印出json ``` printf("The json file:\n\n%s\n", json_object_to_json_string_ext(root, JSON_C_TO_STRING_PRETTY)); ```