json parse
https://github.com/nlohmann/json
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<1>
展开json
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON valuejson j_flattened ={{"/answer/everything", 42},{"/happy", true},{"/list/0", 1},{"/list/1", 0},{"/list/2", 2},{"/name", "Niels"},{"/nothing", nullptr},{"/object/test0", "maya"},{"/object/test1", "houdini"},{"/pi", 3.141}};// call unflatten()std::cout << std::setw(4) << j_flattened.unflatten() << '\n'; // std::cout << j_flattened.dump(4) << '\n'; 不要使用这个方法,这个方法是针对没有linux大纲形式的, }
./out >> test.txt 展开如下。
{"answer": {"everything": 42},"happy": true,"list": [1,0,2],"name": "Niels","nothing": null,"object": {"test0": "maya","test1": "houdini"},"pi": 3.141 }
如何把flat的json转换给当前标准json,并且修改值
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON valuejson j_flattened ={{"/answer/everything", 42},{"/happy", true},{"/list/0", 1},{"/list/1", 0},{"/list/2", 2},{"/name", "Niels"},{"/nothing", nullptr},{"/object/test0", "maya"},{"/object/test1", "houdini"},{"/pi", 3.141}};// call unflatten()std::cout << std::setw(4) << j_flattened.unflatten() << '\n';//std::cout << j_flattened.dump(4) << '\n'; json j = j_flattened.unflatten(); //重新创建新的json对象,这个是标准展开化的std::cout << j.at("answer") <<'\n'; //{"everything":42} 使用at()直接访问。std::cout << j.at("/answer"_json_pointer) <<'\n'; //{"everything":42} 使用_json_pointer访问。std::cout << j.at("/answer"_json_pointer)["everything"] <<'\n'; // 42j.at("answer") = {{"houdini",10}}; // 修改成key valuestd::cout << j.at("answer") <<'\n';j.at("answer") = {11,21,321,21,43}; // 修改成了arraystd::cout << j.at("answer") <<'\n';std::cout << "\n after change to array :\n";std::cout << j.dump(4) <<'\n';return 0; }
输出结果为:
{"answer": {"everything": 42},"happy": true,"list": [1,0,2],"name": "Niels","nothing": null,"object": {"test0": "maya","test1": "houdini"},"pi": 3.141 } {"everything":42} {"everything":42} 42 {"houdini":10} [11,21,321,21,43]after change to array : {"answer": [11,21,321,21,43],"happy": true,"list": [1,0,2],"name": "Niels","nothing": null,"object": {"test0": "maya","test1": "houdini"},"pi": 3.141 }
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<2>JSON Array 操作:
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON arraysjson j_no_init_list = json::array();json j_empty_init_list = json::array({});json j_nonempty_init_list = json::array({1, 2, 3, 4});json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} });// serialize the JSON arraysstd::cout << j_no_init_list << '\n';std::cout << j_empty_init_list << '\n';std::cout << j_nonempty_init_list << '\n';std::cout << j_list_of_pairs << '\n'; }
./out >> test.txt
[] [] [1,2,3,4] [["one",1],["two",2]]
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<3> change value use _json_pointer or change array value use slice
_json_pointer前面必须是以linux / 符号才能改变值
当然at()也能返回值,如果作为返回就为const类型输出。
#include <json.hpp>using json = nlohmann::json;int main() {// create a JSON valuejson j ={{"number", 1},{"string", "foo"},{"array", {1, 2}}};// read-only accessstd::cout << j.dump(4) <<std::endl; // print all as 4 spaces// output element with JSON pointer "/number"std::cout << j.at("/number"_json_pointer) << '\n';// output element with JSON pointer "/string"std::cout << j.at("/string"_json_pointer) << '\n';// output element with JSON pointer "/array"std::cout << j.at("/array"_json_pointer) << '\n';// output element with JSON pointer "/array/1"std::cout << j.at("/array/1"_json_pointer) << '\n';// writing access// change the stringj.at("/string"_json_pointer) = "bar";// output the changed stringstd::cout << j["string"] << '\n';// change an array elementj.at("/array/0"_json_pointer) = 21;j.at("/array/1"_json_pointer) = 31;// output the changed arraystd::cout << j["array"] << '\n'; // print out allstd::cout << j["array"][0] << '\n'; //print first elementstd::cout << j["array"][1] << '\n'; //print secend element// change value direct slice getj["array"][0] = 11;std::cout << j["array"] << '\n'; // print out all }
./out >> text.txt
{ "array": [1,2],"number": 1,"string": "foo" } 1 "foo" [1,2] 2 "bar" [21,31] 21 31 [11,31]
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<4>不用_json_pointer来改变,仅仅使用at(),如果用修改补存在的key-value,则会抛出异常
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON objectjson object ={{"the good", "il buono"},{"the bad", "il cattivo"},{"the ugly", "il brutto"},{"array",{1,2,3,4,5}}};// output element with key "the ugly"std::cout << object.at("the ugly") << '\n';// change element with key "the bad"object.at("the bad") = "il cattivo";object.at("array")[0] = 1000;object.at("/array"_json_pointer)[1] = 2000; //如果使用/ ,才能用_json_pointer// output changed arraystd::cout << object << '\n';// try to write at a nonexisting keytry{object.at("the fast") = "il rapido";}catch (std::out_of_range& e) //修改不存在的值抛出异常{std::cout << "out of range: " << e.what() << '\n';} }
./out >> test.txt
"il brutto"{"array":[1000,2000,3,4,5],"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"} out of range: key 'the fast' not found
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<5>at()按照取标号来改变值,或者取值
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON arrayjson array = {"first", "2nd", "third", "fourth"}; //如果不是key-value形式,则为array,比如{{"first","houdini"},{"next","maya"}}则不是array.测试可以用json.dump(4)方法// output element at index 2 (third element)std::cout << array.at(2) << '\n';// change element at index 1 (second element) to "second"array.at(1) = "second";// output changed arraystd::cout << array << '\n';// try to write beyond the array limittry{array.at(5) = "sixth";}catch (std::out_of_range& e){std::cout << "out of range: " << e.what() << '\n';} }
./out >> test.txt
"third"
["first","second","third","fourth"]
out of range: array index 5 is out of range
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<6>Array和key-value区别
下面是个Array:
json j1={{"first",1000},{"next",1},4,{"niubi",{1,2}}};std::cout << j1.dump(4) << std::endl;
输出结果:
[["first",1000],["next",1],4,["niubi",[1,2]]
]
下面则不是array,但是里面包含array.
json j1={{"first",1000},{"next",1},{"niubi",{1,2}}};std::cout << j1.dump(4) << std::endl;
输出结果:
{
"first": 1000,
"next": 1,
"niubi": [
1,
2
]
}
------------------------------------------------------------------------------------------------------------------------------------------------分界线--------------------------------------------------------------------------------------------------------------------------------------
<7> back方法:
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON values json j_null;json j_boolean = true;json j_number_integer = 17;json j_number_float = 23.42;json j_object = {{"one", 1}, {"two", 20000}};json j_object_empty(json::value_t::object);json j_array = {1, 2, 4, 8, 16};json j_array_empty(json::value_t::array);json j_string = "Hello, world";// call back()//std::cout << j_null.back() << '\n'; // would throwstd::cout << j_boolean.back() << '\n';std::cout << j_number_integer.back() << '\n';std::cout << j_number_float.back() << '\n';std::cout << j_object.back() << '\n'; // 返回的是20000std::cout << j_object.dump(5) << '\n';//std::cout << j_object_empty.back() << '\n'; // undefined behaviorstd::cout << j_array.back() << '\n'; // 16std::cout << j_array.dump(5) << '\n';//std::cout << j_array_empty.back() << '\n'; // undefined behaviorstd::cout << j_string.back() << '\n';std::cout << j_string.dump(5) <<std::endl; }
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<8>
复制构造函数copy
#include <json.hpp>using json = nlohmann::json;int main() {// create a JSON arrayjson j1 = {"one", "two", 3, 4.5, false};// create a copy json j2(j1);// serialize the JSON arraystd::cout << j1 << " = " << j2 << '\n';std::cout << std::boolalpha << (j1 == j2) << '\n'; // std::boolalpha 是让判断条件输出false or true,默认输出 0 1 }
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<9>类型支持,容器,变量
#include <json.hpp> #include <map> #include <iostream> #include <unordered_map> #include <vector> #include <list> #include <deque> using json = nlohmann::json;int main() {json::object_t obj_val = {{"one",1},{"two",2}};json obj(obj_val);std::cout << obj.dump(4) <<std::endl;// 和stl_map 一起使用std::map<std::string,int> map_val = {{"h0",0},{"h1",1}};map_val["h2"] = 2;map_val["h3"] = 3;map_val.insert(std::pair<std::string, int>("h4", 4));std::pair<std::string,int> h5 = std::pair<std::string,int>("h5",5);map_val.insert(h5);std::pair<std::string,int> h6 = std::make_pair("h6",6);map_val.insert(h6);std::map<std::string,int>::value_type h7("h7",7); // value_type is the std::pair map_val.insert(h7);// iterator the mapfor(std::map<std::string,int>::iterator it = map_val.begin();it!=map_val.end();++it){std::cout << "iter map -> "<<it->first << " : " << it->second <<'\n';}json jmap_val(map_val);std::cout << jmap_val.dump(4) << std::endl;//无序mapstd::unordered_map<const char *,double > obj_unmap ={{"one", 1.2}, {"two", 2.3}, {"three", 3.4}};json j_umap(obj_unmap);std::cout << j_umap.dump(4) <<std::endl;// 可以重复key-valuestd::multimap<std::string, bool> c_mmap ={{"one", true}, {"two", true}, {"three", false}, {"three", true}};// 如果放入json ,只会解析一个three json j_mmap(c_mmap);std::cout << j_mmap.dump(4) <<std::endl;// create an array from an array_t valuejson::array_t array_value = {"one", "two", 3, 4.5, false};json j_array_t(array_value);std::cout << "json::array_t :\n" << j_array_t.dump(4) <<std::endl;// create an array from std::vectorstd::vector<int> c_vector {1, 2, 3, 4};json j_vec(c_vector);std::cout << "json from vector :\n" << j_vec.dump(4) <<std::endl;// create an array from std::dequestd::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};json j_deque(c_deque);// create an array from std::liststd::list<bool> c_list {true, true, false, true};json j_list(c_list);// create an array from std::forward_liststd::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};json j_flist(c_flist);// stringjson::string_t string_value = "The quick brown fox jumps over the lazy dog.";json j_string_t(string_value);json j_string_literal("The quick brown fox jumps over the lazy dog.");std::cout << j_string_literal.dump(4) <<std::endl;//numjson::number_integer_t value_integer_t = -42;json j_integer_t(value_integer_t);std::cout << j_integer_t.dump(4) <<std::endl;json j_truth = true;json j_falsity = false;json j_float = 1.000001f;json j_float2(2.0f);std::cout << j_float.dump(4) <<std::endl;std::cout << j_float2.dump(4) <<std::endl;return 1; }
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<10>容器迭代,变量
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON valuesjson j_array = {"alpha", "bravo", "charly", "delta", "easy"};json j_number = 42;json j_object = {{"one", "eins"}, {"two", "zwei"}};// create copies using iteratorsjson j_array_range(j_array.begin() + 1, j_array.end() - 2);json j_array_range2(j_array.end() - 2, j_array.end());json j_number_range(j_number.begin(), j_number.end());json j_object_range(j_object.begin(), j_object.find("two"));// serialize the valuesstd::cout << j_array_range << '\n';std::cout << j_array_range2 << '\n';std::cout << j_number_range << '\n';std::cout << j_object_range << '\n'; }
输出:
["bravo","charly"]
["delta","easy"]
42
{"one":"eins"}
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<11>如何过滤不需要的key,使用call back方法
#include <json.hpp>using json = nlohmann::json;int main() {// a JSON textauto text = R"( {"Image": {"Width": 800,"Height": 600,"Title": "View from 15th Floor","Thumbnail": {"Url": "http://www.example.com/image/481989943","Height": 125,"Width": 100},"Animated" : false,"IDs": [116, 943, 234, 38793]}})";// fill a stream with JSON text std::stringstream ss;ss << text;// create JSON from streamjson j_complete(ss); // deprecated! 不赞成的做法// shall be replaced by: json j_complete = json::parse(ss);//std::cout << std::setw(4) << j_complete << "\n\n";std::cout << j_complete.dump(4) << "\n\n"; // same as up line 和上面的语句意思相同// define parser callbackjson::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed){// skip object elements with key "Thumbnail"if (event == json::parse_event_t::key and parsed == json("Thumbnail")){return false;}else{return true;}};// fill a stream with JSON text ss.clear();ss << text;// create JSON from stream (with callback) json j_filtered(ss, cb);// shall be replaced by: json j_filtered = json::parse(ss, cb);std::cout << std::setw(4) << j_filtered << '\n'; }
输出:
{"Image": {"Animated": false,"Height": 600,"IDs": [116,943,234,38793],"Thumbnail": {"Height": 125,"Url": "http://www.example.com/image/481989943","Width": 100},"Title": "View from 15th Floor","Width": 800} }{"Image": {"Animated": false,"Height": 600,"IDs": [116,943,234,38793],"Title": "View from 15th Floor","Width": 800} }
------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------
<12>区别类型
#include <json.hpp>using json = nlohmann::json;int main() {// create JSON valuesjson j_empty_init_list = json({}); //empty nulljson j_object = { {"one", 1}, {"two", 2} };json j_array = {1, 2, 3, 4}; // arrayjson j_nested_object = { {"one", {1}}, {"two", {1, 2}} }; // key-value(array)json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} }; // 总体为array// serialize the JSON valuestd::cout << j_empty_init_list << '\n';std::cout << j_object << '\n';std::cout << j_array << '\n';std::cout << j_nested_object << '\n';std::cout << j_nested_array << '\n'; }
转载于:https://www.cnblogs.com/gearslogy/p/6479704.html
json parse相关推荐
- JSON.parse解析特殊字符报错解决方案
2019独角兽企业重金招聘Python工程师标准>>> 具体案例: 页面点击"下一任务" 会去请求后台,这里出现的问题是有虚拟任务的时候.然后会返回一个map,也 ...
- JSON.parse 函数应用 (复制备忘)
JSON.parse 函数 JSON.parse 函数 (JavaScript) 将 JavaScript 对象表示法 (JSON) 字符串转换为对象. 语法 JSON.parse(text [, r ...
- php json.parse,PHP JSON头导致JSON.parse出错(使用jQuery)
我正在从PHP文件中获取一些JavaScript格式的JSON数据. 要使用这些数据,我使用JSON.parse(json_response),除了在PHP中使用JSON头之外,它都可以工作:head ...
- json.parse()和json.stringify()
json.parse() 用于从一个字符串解析出json对象 var str = '{"name":"huangzhong","age":& ...
- JSONObject JSONArray各种用法以及js eval()函数与JSON.parse的区
2019独角兽企业重金招聘Python工程师标准>>> 一.在后台使用JSONObject对象,并将从数据库中取出来的数据直接使用 JSONObject的put方法放进去,再将这个J ...
- JSON.parse()出错解决
在做微信小程序时遇到的问题,记录一下. 需求: 将购物车页面的商品信息通过url传到确认订单页 复制代码 购物车页面处理过程: 在购物车页面,处理商品信息组装成如下形式: goodsInfoArr = ...
- 【前端】JSON.stringfy 和 JSON.parse(待续)
JSON.stringfy 和 JSON.parse(待续) 支持全局对象JSON的浏览器有:IE8+, FireFox3.5+, Safari4+, Chrome, Opera10.5+ JSON. ...
- 理解JSON对象:JSON.parse、 JSON.stringify
何时是JSON,何时不是JSON? JSON就是一个有特殊规则的字符串,按照这个规则我们就可以把这个字符串解析成JS对象. JSON是设计成描述数据交换格式的,他也有自己的语法,这个语法是JavaSc ...
- JSON.parse()和eval()的区别
json格式非常受欢迎,而解析json的方式通常用JSON.parse()但是eval()方法也可以解析,这两者之间有什么区别呢? JSON.parse()之可以解析json格式的数据,并且会对要解析 ...
- JSON.stringify()和JSON.parse()分别是什么
JSON.stringify() 从一个对象中解析出字符串 JSON.stringify({"a":"1","b":"2" ...
最新文章
- mysql分表搜索引擎_MySql分库分表总结(转)
- 快速傅里叶变换(FFT)算法【详解】
- Java入门之初识设计模式---单列模式
- python format 字典_python 用字典格式化字符串
- 在Oracle Linux 7上通过官方Repo在线安装SQL Server 2017
- 非spring托管对象如何获取到spring托管对象
- 网上赚钱最快的方法 干什么能挣钱快
- ecshop 框架 简单分析
- 基于Outline构建团队的知识库 (上篇)
- python中空字符串是什么_python为空怎么表示 python如何判断字符串为空
- Python 截屏 - lone112 - 博客园
- 像人一样自然流畅地说话,下一代智能对话系统还有多长的路要走?
- 【大数据】为什么要学习大数据
- 总是封群怎么解决_我的群被封了怎么办
- angular js 循环数据(死数据) 添加数据 隔行换色 单个删除 排序
- 完美解决React 注册模块报错Missing message: “menu.xxx“ for locale: “zh-CN“, using default message as fallback问题
- 麦克纳姆轮(麦轮)原理
- 苹果首席设计师Jony Ive离职 真正的原因究竟是什么?
- [RPi]树莓派GPIO入门之控制LED灯
- ThinkPad知识大全