nlohmann簡(jiǎn)介
nlohmann json GitHub - nlohmann/json: JSON for Modern C++ 是一個(gè)為現(xiàn)代C++(C++11)設(shè)計(jì)的JSON解析庫(kù),主要特點(diǎn)是:
1、易于集成,僅需一個(gè)頭文件,無(wú)需安裝依賴
2、易于使用,可以和STL無(wú)縫對(duì)接,使用體驗(yàn)近似python中的json
安裝
Linux下:
git clone https://github.com/nlohmann/json.git
拉取nlohmann庫(kù)文件
使用
自己建立一個(gè)項(xiàng)目工程文件夾,將include下的molhmann文件夾復(fù)制到自己工程下的include文件夾下
。
測(cè)試工程文件結(jié)構(gòu):
測(cè)試的json文件
{
"pi":3.1415,
"happy":true
}
主文件
#include "nlohmann/json.hpp"
#include <fstream>
#include <iostream>
using json = nlohmann::json;
int main(int argc,char *argv[]) {
json j; // 創(chuàng)建 json 對(duì)象
if(argc == 1){
std::ifstream jfile("./test/test.json");
jfile >> j; // 以文件流形式讀取 json 文件
}
else if(argc == 2){
std::ifstream jfile(argv[1]);
jfile >> j; // 以文件流形式讀取 json 文件
}
else{
std::cout << "ERROR: Parameters are too many!" << std::endl;
return -1;
}
float pi = j.at("pi");
bool happy = j.at("happy");
std::cout << "pi: " << pi << std::endl;
std::cout << "happy: " << happy << std::endl;
return 0;
}
編寫build.sh腳本文件
#!/bin/bash
US="../"
cd $US
g++ ./Parse/parse.cpp -I ./include -o ./bin/parse
在build目錄下給build.sh運(yùn)行權(quán)限,以bash運(yùn)行
chmod 755 build.sh
然后
./build.sh
會(huì)在工程文件夾的bin目錄下生成可執(zhí)行文件parse
編寫run.sh腳本文件
#!/bin/bash
FILENAME="test.json"
./parse ../test/${FILENAME}
在bin目錄下給run.sh運(yùn)行權(quán)限,以bash運(yùn)行
chmod 755 build.sh
然后
./run.sh
結(jié)果輸出:
pi: 3.1415
happy: 1
注意:如果想要更改測(cè)試文件,只需要將run.sh文件中FILENAME="test.json"
引號(hào)中的文件名改成想要測(cè)試的文件名即可。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-847176.html
具體語(yǔ)法文檔:https://github.com/nlohmann/json/blob/develop/README.md
中文簡(jiǎn)易版語(yǔ)法文檔可以參考:https://www.cnblogs.com/linuxAndMcu/p/14503341.html文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-847176.html
到了這里,關(guān)于[C++ Json開(kāi)源庫(kù)] nlohmann安裝與使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!