nlohmann简介

nlohmann json GitHub - nlohmann/json: JSON for Modern C++ 是一个为现代C++(C++11)设计的JSON解析库,主要特点是:

1、易于集成,仅需一个头文件,无需安装依赖
2、易于使用,可以和STL无缝对接,使用体验近似python中的json

安装

Linux下:

git clone https://github.com/nlohmann/json.git

拉取nlohmann库文件

使用

自己建立一个项目工程文件夹,将include下的molhmann文件夹复制到自己工程下的include文件夹下

测试工程文件结构:

在这里插入图片描述

测试的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;			// 创建 json 对象
    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运行权限,以bash运行

chmod 755 build.sh

然后

./build.sh

会在工程文件夹的bin目录下生成可执行文件parse

编写run.sh脚本文件

#!/bin/bash
FILENAME="test.json"
./parse ../test/${FILENAME}

在bin目录下给run.sh运行权限,以bash运行

chmod 755 build.sh

然后

./run.sh

结果输出:

pi: 3.1415
happy: 1

注意:如果想要更改测试文件,只需要将run.sh文件中FILENAME="test.json"引号中的文件名改成想要测试的文件名即可。

具体语法文档:https://github.com/nlohmann/json/blob/develop/README.md
中文简易版语法文档可以参考:https://www.cnblogs.com/linuxAndMcu/p/14503341.html

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐