# C++ JSON File <br /> 簡單使用指北
###### Author: tico88612
---
## 前置任務
----
當然是先安裝 MinGW + VSCode 設定
https://blog.yangjerry.tw/2021/09/24/vscode-cpp-2021-part1/
----
VSCode IntelliSence + GDB
https://blog.yangjerry.tw/2021/09/26/vscode-cpp-2021-part2/
---
## Install
https://github.com/nlohmann/json
----
https://github.com/nlohmann/json/#integration
----
前面連結點下去,怕爆.jpg
Visual Studio 就直接去 NuGet 下載套件就可以使用了。
----
想更簡單一點,直接 simple_include/nlohmann 裡面抓到 json.hpp
就可以 `#include "nlohmann/json.hpp"`
----
### Demo
---
## Usage
----
```
├── blood-pressure-input.json
├── main.cpp
├── main.exe
└── nlohmann
└── json.hpp
```
----
main.cpp
```cpp=
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main()
{
json j;
j["123"] = 123;
std::cout << j << std::endl;
return 0;
}
```
---
## Application
----
HL7 FHIR Observation Blood Pressure
https://www.hl7.org/fhir/observation-example-bloodpressure.json.html
之後可能就用 QT C++ 的 Function 或 cURL 先下載之類的
這裡只示範怎麼用純 C++ 去讀取
----
上面的 example 做為 blood-pressure-input.json
----
C++ 檔案讀取
```cpp=
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
int main()
{
std::ifstream ifs("blood-pressure-input.json");
nlohmann::json BPD = nlohmann::json::parse(ifs); // Blood Pressure Data
std::cout << std::setw(2) << BPD << std::endl;
return 0;
}
```
----
確認他可以讀取成功,那就來做更進階的讀取。
如果你知道 JavaScript 的 JSON 怎麼讀取,這裡就怎麼讀取。
這裡的 Code 僅且示範怎麼拿取資料,最好還是把這些資料做成 Object Class。
----
讀取測量時間
```cpp=
std::string measureDate = BPD["effectiveDateTime"].get<std::string>();
std::cout << "Effective DateTime: " << measureDate << std::endl;
```
----
讀取測量部位
```cpp=
std::string bs = BPD["bodySite"]["coding"][0]["display"].get<std::string>();
std::cout << "Body Site: " << bs << std::endl;
```
----
測量狀況
```cpp=
std::string total_interpretation = BPD["interpretation"][0]["text"].get<std::string>();
std::cout << "Interpretation status: " << total_interpretation << std::endl;
```
----
將多筆數值讀取(包含收縮壓、舒張壓)
```cpp=
auto component = BPD["component"];
for (auto& it: component) {
std::string display = it["code"]["coding"][0]["display"].get<std::string>();
std::string unit = it["valueQuantity"]["unit"].get<std::string>();
std::cout << display << ": " << it["valueQuantity"]["value"] << " " << unit << std::endl;
std::string interpretation = it["interpretation"][0]["coding"][0]["display"].get<std::string>();
std::cout << "Status: " << interpretation << std::endl;
}
```
---
## Thank you!
{"metaMigratedAt":"2023-06-16T14:30:00.307Z","metaMigratedFrom":"YAML","title":"C++ JSON File 簡單使用指北","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"e7e2d13b-b3cd-4b2f-949d-2791f1df95a3\",\"add\":10048,\"del\":7386}]"}