AlgebraMaster

Modern C++ 创造非凡 . 改变世界

导航

json parse

https://github.com/nlohmann/json

 ------------------------------------------------------------------------------------------------------------------------------------------------ 分界线 --------------------------------------------------------------------------------------------------------------------------------------

<1>

展开json

#include <json.hpp>

using json = nlohmann::json;

int main()
{
    // create JSON value
    json 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 value
    json 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'; // 42
    j.at("answer") = {{"houdini",10}}; // 修改成key value
    std::cout << j.at("answer") <<'\n';
    j.at("answer") = {11,21,321,21,43}; // 修改成了array
    std::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 arrays
    json 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 arrays
    std::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 value
    json j =
            {
                    {"number", 1},
                    {"string", "foo"},
                    {"array", {1, 2}}
            };

    // read-only access
    std::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 string
    j.at("/string"_json_pointer) = "bar";
    // output the changed string
    std::cout << j["string"] << '\n';

    // change an array element
    j.at("/array/0"_json_pointer) = 21;
    j.at("/array/1"_json_pointer) = 31;
    // output the changed array
    std::cout << j["array"] << '\n';   // print out all
    std::cout << j["array"][0] << '\n'; //print first element
    std::cout << j["array"][1] << '\n'; //print secend element

    // change value direct slice get
    j["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 object
    json 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 array
    std::cout << object << '\n';

    // try to write at a nonexisting key
    try
    {
        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 array
    json 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 array std::cout << array << '\n'; // try to write beyond the array limit try { 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 throw
    std::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'; // 返回的是20000
    std::cout << j_object.dump(5) << '\n';
    //std::cout << j_object_empty.back() << '\n';  // undefined behavior
    std::cout << j_array.back() << '\n';   // 16
    std::cout << j_array.dump(5) << '\n';
    //std::cout << j_array_empty.back() << '\n';   // undefined behavior
    std::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 array
    json j1 = {"one", "two", 3, 4.5, false};

    // create a copy
    json j2(j1);

    // serialize the JSON array
    std::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 map
    for(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;

    //无序map
    std::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-value
    std::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 value
    json::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::vector
    std::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::deque
    std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
    json j_deque(c_deque);

    // create an array from std::list
    std::list<bool> c_list {true, true, false, true};
    json j_list(c_list);

    // create an array from std::forward_list
    std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
    json j_flist(c_flist);

    // string
    json::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;
    //num
    json::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 values
    json j_array = {"alpha", "bravo", "charly", "delta", "easy"};
    json j_number = 42;
    json j_object = {{"one", "eins"}, {"two", "zwei"}};

    // create copies using iterators
    json 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 values
    std::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 text
    auto 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 stream
    json 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 callback
    json::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 values
    json j_empty_init_list = json({}); //empty null
    json j_object = { {"one", 1}, {"two", 2} };
    json j_array = {1, 2, 3, 4};  // array
    json j_nested_object = { {"one", {1}}, {"two", {1, 2}} }; // key-value(array)
    json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} }; // 总体为array

    // serialize the JSON value
    std::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';
}

 

posted on 2017-02-28 17:03  gearslogy  阅读(1532)  评论(0编辑  收藏  举报