Json 学习笔记
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。
本文大致介绍一个较为使用的json开源库。json开源库
常用方法
1.首先要引入json作用域。
using json = nlohmann::json;
json提供了cin,cout的输入输出流的操作符。但需要注意的是,cin要有ctr + D结束输入。cout会自动把json转换为string。
#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
using std::cout;
using std::endl;
using std::cin;
int main(int argc, const char * argv[]) {
json temp;
cin >> temp;
cout << temp << endl;
return 0;
}
/*
输入:
{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}
{
"answer":{
"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{
"currency":"USD","value":42.99},"pi":3.141}
Program ended with exit code: 0
*/
2. 键值对
提供根据键直接生成键值对的方法。(类似于map,如果不存在该键的话,就生成一个这个键。)
#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
using std::cout;
using std::endl;
using std::cin;
int main(int argc, const char * argv[]) {
// 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}
}}
};
cout << j << endl;
cout << endl;
cout << j2 << endl;
return 0;
}
/*
{
"answer":{
"everything":