c++ nlohmann/json 及修改json文件中个别关键字

(2条消息) nlohmann json使用_nlohmann::json_蜗牛单行道的博客-CSDN博客json为JavaScript object notation 是一种数据格式,逐渐替换掉了传统的xml 。json数据格式的属性名称和字符串值需要用双引号引起来,用单引号或者不用引号会导致读取数据错误。json的另外一个数据格式是数组,和javascript中的数组字面量相同。

使用Json的格式与解析方便的可以表示一个对象信息,json有两种格式:

json中不能有注释,undefined,只要涉及到字符串的就必须双引号

①对象格式:{"key1":obj,"key2":obj,"key3":obj...}、

②数组/集合格式:[obj,obj,obj...]。

json.parse()解析将字符串解析成对应的值,

例子:

nlohmann/json: JSON for Modern C++ (github.com)

 中代码下载下来,然后将include文件夹添加到测试工程的包含路径下即可:

我是用的绝对路径:D:\excer\mfc\json\json\include\; 

 测试代码:

#include <iostream>
#include <fstream>
#include <ostream>
#include "json.hpp"
using json = nlohmann::json;

int main()
{
    std::cout << "Hello World!\n";

	//读取json文件--------------------------------
	std::ifstream f("example.json");
	json data = json::parse(f);
	double pi = data["pi"];
	bool td = false; 
	//td = data["happy"];
	if (!data["happy"].is_null())
	{
		td = data["happy"];
	}
	std::string sname = data["name"].get<std::string>(); ;
	std::cout << data;
	int c = 0;

	//输出json文件--------------------------------
	// create an empty structure (null)
	json j;

    //方式一---------------------------------------
	// add a number that is stored as double (note the implicit conversion of j to an object)
	j["pi"] = 3.141;

	// add a Boolean that is stored as bool
	j["happy"] = true;

	// add a string that is stored as std::string
	j["name"] = "Niels";

	// add another null object by passing nullptr
	j["nothing"] = nullptr;

	// add an object inside the object
	j["answer"]["everything"] = 42;

	// add an array that is stored as std::vector (using an initializer list)
	j["list"] = { 1, 0, 2 };

	// add another object (using an initializer list of pairs)
	j["object"] = { {"currency", "USD"}, {"value", 42.99} };

    //方式二---------------------------------------
	// instead, you could also write (which looks very similar to the JSON above)
	json j2 = {
	  {"pi", 3.141},
	  {"happy", true},
	  {"name", "Niels"},
	  {"nothing", nullptr},
	  {"answer", {
		{"everything", 42}
	  }},
	  {"list", {1, 0, 2}},
	  {"object", {
		{"currency", "USD"},
		{"value", 42.99}
	  }}
	};

	//输出到文件中
	std::ofstream fout("out.json");
	fout << std::setw(4)<< j;
	fout << std::setw(4) << j2;
	fout.close();

}

对应的:json格式

{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}

 异常处理:

标签(关键字)happy2不存在,只有标签(关键字)happy,如果执行该语句bool td = data["happy2"]; 在直接读取标签happy2则解析器会崩溃。

解决办法:下面先对标签判断一下是否为空,为空的话,就不要直接读取了。 标签不为空才能直接读取

//td = data["happy"];
	if (!data["happy"].is_null())//关键字不为空才能直接读取
	{
		td = data["happy"];
	}

或者用contain

if (js.contains("exposure"))
	{
		// expos = js["exposure"];//不建议
		//.get<std::string>()
		expos = js["exposure"].get<int>();//建议显示类型转换
		strTemp.Format(L"%d", expos);
		SetDlgItemText(IDC1_EDIT1, strTemp);;
	}

 异常2:修改json文件中个别关键字时

按照直接修改js["exposure"] = expos;写到json文件时,文件会出现重复的关键字,后面json再读取解析文件时就会崩溃,解决办法为: 先读json文件,然后解析,解析后赋值给中间变量,

修改中间变量中的关键字,然后再保存json文件就可以了。

std::ifstream ifs("config.json", std::ios::app);//先读json文件
	json ss = json::parse(ifs);//解析json文件
	json js = ss;//中间变量js
	//js = ss;
	CString strTemp;
	GetDlgItemText(IDC1_EDIT1, strTemp);
	int expos = _ttoi(strTemp);
	if (js.contains("exposure"))
	{
		js["exposure"] = expos;//修改中间变量js中关键字exposure
	}
	

	std::ofstream fs("config.json");//最后写json文件
	fs << std::setw(4)<< js << std::endl;;//setw(4) 是用于打印格式好看的 json 文件//使用 j.dump(4) 也是一样的效果
	//fs <<  js;
	fs.close();

参考:

Issues · nlohmann/json (github.com)https://github.com/nlohmann/json/issues/1475

主要看下面的文章:

写json格式

c++中nlohmann json的基本使用教程_C 语言_脚本之家 (jb51.net)

nlohmann/json: JSON for Modern C++ (github.com)https://github.com/nlohmann/json/tree/develop

JSON的三种格式https://blog.csdn.net/daxiong0816/article/details/125132404

json格式 (keoaeic.org)https://mip.keoaeic.org/unscramble_major/4394.htmlC++ json格式的书写_雪星途的博客-CSDN博客https://blog.csdn.net/weixin_45387966/article/details/122469835

(2条消息) nlohmann json使用_nlohmann::json_蜗牛单行道的博客-CSDN博客https://blog.csdn.net/qq_39568245/article/details/115312690?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-115312690-blog-121181848.235%5Ev38%5Epc_relevant_anti_vip_base&spm=1001.2101.3001.4242.1&utm_relevant_index=3

猜你喜欢

转载自blog.csdn.net/u012719076/article/details/131167667