Skip to content
/ json Public

A simple and easy-to-use JSON library of less than 800 lines

License

Notifications You must be signed in to change notification settings

yaomer/json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

使用时只需要简单包含json.h即可。

然后需要使用c++17来编译。

$ clang++ -std=c++17 json-check.cc

json-checker用于测试parse是否能正常工作。


假如我们有以下json文件,就叫做m.json吧。

{
    "name": "Bob",
    "age": 32,
    "langs": [
        "java",
        "go",
        "c"
    ],
    "scores": {
        "math": "A",
        "physics": "A",
        "computer": "B"
    }
}

parse

#include "json.h"

#include <iostream>

using namespace std;

int main()
{
    json::value jv;
    jv.parsefile("m.json");
    cout << jv.at("name").as_string().c_str() << "\n";
    cout << jv.at("age").as_number() << "\n";
    cout << jv.at("langs").at(0).as_string().c_str() << "\n";
    cout << jv.at("langs").at(1).as_string().c_str() << "\n";
    cout << jv.at("langs").at(2).as_string().c_str() << "\n";
    cout << jv.at("scores").at("math").as_string().c_str() << "\n";
    cout << jv.at("scores").at("physics").as_string().c_str() << "\n";
    cout << jv.at("scores").at("computer").as_string().c_str() << "\n";
}

使用[]at没有什么不同,只不过我觉得at从视觉上更一致些。

你也可以像使用stl那样遍历数组对象

int main()
{
    json::value jv;
    jv.parsefile("m.json");
    for (auto& lang : jv.at("langs").as_array()) {
        cout << lang->as_string().c_str() << "\n";
    }
    for (auto& [name, score] : jv.at("scores").as_object()) {
        cout << name.c_str() << ", " << score->as_string().c_str() << "\n";
    }
}

dump

int main()
{
    json::value jv;
    jv.at("name") = "Bob";
    jv.at("age") = 32;
    jv.at("langs") = { "java", "go", "c" };
    jv.at("scores").at("math") = "A";
    jv.at("scores").at("physics") = "A";
    jv.at("scores").at("computer") = "B";
    string s;
    jv.dump(s, 2); // 可视化输出,以2空格缩进。
    cout << s.c_str() << "\n";
}

对于数组,你也可以使用append,但不能像对象那样通过at(i) = val来添加一个新的val

int main()
{
    json::value jv;
    jv.append("A").append("B").append("C"); // true
    jv.at(0) = "hello"; // modify, ok

    json::value jv1;
    jv1.at(0) = "A"; // false
}

About

A simple and easy-to-use JSON library of less than 800 lines

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages