C++:json解析库

比较简单好用的轻量级的库

保存在我的资源里了,当然网上也都可以下到

configor:json解析库forC++-C++文档类资源-CSDN下载

只有这级目录的文件

使用配置,只需要设置一下头文件包含目录即可

 

 使用如下:

#include <iostream>
#include <fstream>
#include <string>
#include <configor/json.hpp>

using namespace std;
using configor::json;

int main()
{
	json output_json_data;
	output_json_data["id"] = 1;
	output_json_data["value"] = { 3.1415 , 0.618};
	string name[4] = {};
	name[0] = "zhangsan";
	name[1] = "lisi";
	name[2] = "wangwu";
	output_json_data["name"] = name;


	std::ofstream myfile("myjson.json");
	
	//可以直接将json对象输出到文件
	myfile << std::setw(4) << output_json_data << std::endl;

	//也可以直接输出到终端
	cout << output_json_data << endl;

	string str = output_json_data.dump();
	cout << str << endl;

	string json_name = "myjson.json";
	//打开json
	ifstream input_json_file(json_name);
	//解析json
	json json_data;
	input_json_file >> json_data;
	input_json_file.close();

	int id = json_data["id"];
	double value[2] = {};
	value[0] = json_data["value"][0];
	value[1] = json_data["value"][1];

	string NAME = json_data["name"][0];
	
	cout << id << endl;
	cout << value[0] << endl;
	cout << value[1] << endl;
	cout << NAME << endl;
	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
nlohmann::json是一个开源的C++,用于解析和处理JSON数据。它提供了简单易用的API,可以方便地将JSON数据解析C++对象,并且可以轻松地将C++对象转换为JSON格式。 要使用nlohmann::json解析文件,首先需要包含头文件`#include <nlohmann/json.hpp>`。然后,可以使用`nlohmann::json`类型的对象来表示JSON数据,并使用该对象的成员函数来解析文件。 以下是解析文件的基本步骤: 1. 打开文件并读取JSON数据。 2. 使用`nlohmann::json`对象来解析JSON数据。可以使用`json::parse()`函数将JSON字符串解析为`nlohmann::json`对象。 3. 使用`nlohmann::json`对象的成员函数来访问和处理JSON数据。 下面是一个简单的示例代码,演示了如何使用nlohmann::json解析文件: ```cpp #include <iostream> #include <fstream> #include <nlohmann/json.hpp> int main() { // 打开文件并读取JSON数据 std::ifstream file("data.json"); std::string jsonData((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); // 使用nlohmann::json对象解析JSON数据 nlohmann::json json = nlohmann::json::parse(jsonData); // 访问和处理JSON数据 std::string name = json["name"]; int age = json["age"]; // 输出解析结果 std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; return 0; } ``` 请注意,上述示例代码假设文件名为"data.json",并且文件中包含以下JSON数据: ```json { "name": "John", "age": 25 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值