json parse

Posted AlgebraMaster

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

./out >> test.txt 展开如下。

{
    "answer": {
        "everything": 42
    },
    "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"};

    // 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>

 




以上是关于json parse的主要内容,如果未能解决你的问题,请参考以下文章

解析:JSON 文本没有以数组或对象开头,并且允许未设置片段的选项

如何在笑话测试中模拟 json.parse()

保存语法和 JSON.parse 代码时出错

为啥 JSON.parse 会抛出跨域错误?

node json.parse和querystring.parse的区别

从一个 JSON.parse 错误深入研究 JavaScript 的转义字符