使用rapidjson Json解析

前言

随便写写,自己经常用到;官方教程比我详细.

安装

sudo apt-get install rapidjson-dev

这个库完全是通过头文件实现的,直接拷贝到头文件的文件夹 also can do it.

内存流

输入

StringStream

#include 
#include 

using namespace std;

int main(int, char **)
{
    const char *json = "{\"hello\" : \"ligoudan\"}";
    rapidjson::StringStream input(json);
    rapidjson::Document document;
    document.ParseStream(input);

    cout << document["hello"].GetString() << endl;

    return 0;
}

输出

StringBuffer

#include 
#include 
#include 
#include 

using namespace std;

int main(int, char **)
{
    rapidjson::Document document;
    rapidjson::Document::AllocatorType &allocator = document.GetAllocator();
    document.SetObject();

    rapidjson::Value name;
    name.SetString("misaka");

    document.AddMember("name", name, allocator);

    // output
    rapidjson::StringBuffer SB;
    rapidjson::Writer writer(SB);
    document.Accept(writer);

    cout << SB.GetString() << endl;

    return 0;
}

文件流

输入

文件

{
    "hello": "world",
    "t": true,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}

呆马

#include 
#include 
#include 
#include 

using namespace std;

int main(int, char **)
{
    FILE *fp = fopen("input.json", "r"); // stupid windows need rb
    char buf[0XFFFF];

    //FileReadStream(FILE *fp, char *buffer, std::size_t bufferSize)
    rapidjson::FileReadStream input(fp, buf, sizeof(buf));
    rapidjson::Document document;
    document.ParseStream(input);
    fclose(fp);

    cout << boolalpha;
    cout << document["hello"].GetString() << endl;
    cout << document["t"].GetBool() << endl;
    cout << (document["n"].IsNull() ? "null" : "He He") << endl;
    cout << document["pi"].GetDouble() << endl;

    return 0;
}

输出

格式有点小问题

#include 
#include 
#include 
#include 


using namespace std;

int main(int, char **)
{
    rapidjson::Document document;
    rapidjson::Document::AllocatorType &allocator = document.GetAllocator();
    document.SetObject();

    rapidjson::Value hello;
    hello.SetString("world");

    rapidjson::Value t;
    t.SetBool(true);

    rapidjson::Value f(false);

    rapidjson::Value n;
    n.SetNull();

    rapidjson::Value i(123);
    rapidjson::Value pi(3.1416);

    rapidjson::Value a;
    a.SetArray();
    for (int i = 0; i < 4; ++i) {
        a.PushBack(i+1, allocator);
    }

    document.AddMember("hello", hello, allocator);
    document.AddMember("t", t, allocator);
    document.AddMember("f", f, allocator);
    document.AddMember("n", n, allocator);
    document.AddMember("i", i, allocator);
    document.AddMember("pi", pi, allocator);
    document.AddMember("a", a, allocator);

    //output
    FILE *fp = fopen("output.json", "w"); // stupid win need wb

    char buf[0XFFFF];
    // FileWriteStream(FILE *fp, char *buffer, std::size_t bufferSize)
    rapidjson::FileWriteStream output(fp, buf, sizeof (buf));
    rapidjson::Writer writer(output);
    document.Accept(writer);

    fclose(fp);

    return 0;
}

常用操作(抄一遍教程)

#include 
#include 
#include 
#include 

// #define NDEBUG
#include 

void for_each_json(const rapidjson::Document &document);

using namespace std;

int main(int, char **)
{
    cout << boolalpha;

    rapidjson::Document document;
    rapidjson::Document::AllocatorType &allocator = document.GetAllocator();
    document.SetObject();

    assert(document.IsObject());

    // 查找有没有name
    cout << "name=" <<
        (document.HasMember("name") ? document["name"].GetString() : "没有")
         << endl;

    // fill
    rapidjson::Value hello("world");
    rapidjson::Value t(true);
    rapidjson::Value f(false);
    rapidjson::Value n;
    n.SetNull();
    rapidjson::Value i(123);
    rapidjson::Value pi(3.1416);
    // 暂时先不fill array 因为不会...
    rapidjson::Value a;
    a.SetArray();

    // add member
    // NOTE rapidjson为了性能,AddMember执行之后会让Value变成null
    document.AddMember("hello", hello, allocator);
    document.AddMember("t", t, allocator);
    document.AddMember("f", f, allocator);
    document.AddMember("i", i, allocator);
    document.AddMember("n", n, allocator);
    document.AddMember("pi", pi, allocator);
    document.AddMember("a", a, allocator);

    // try
    assert(document["hello"].IsString());
    assert(document["t"].IsBool());
    assert(document["n"].IsNull());
    assert(document["i"].IsInt());
    assert(document["i"].IsNumber());
    assert(document["pi"].IsDouble());
    assert(document["a"].IsArray());

    // get
    cout << document["hello"].GetString() << endl;
    cout << document["t"].GetBool() << endl;
    cout << document["f"].GetBool() << endl;
    cout << (document["n"].IsNull() ? "null" : "SB") << endl;
    cout << document["i"].GetInt() << endl;
    cout << document["pi"].GetDouble() << endl;

    cout << "-*-*-*-*-*-华丽的分割线-*-*-*-*-*-" << endl;

    // fill array
    rapidjson::Value &array = document["a"]; // 因为a已经变成废铁了
    /**
     * 关于Array的基本操作
     * Clear();
     * Value & PushBack(Value &, Allocator &);
     * template  GenericValue & PushBack(T, Allocator &);
     * Value & PopBack();
     * ValueIterator Erase(ConstValueIterator pos);
     * ValueIterator Erase(ConstValueIterator first, ConstValueIterator last);
     */
    for (int i = 0; i < 4; ++i) {
        array.PushBack(i, allocator);
    }

    // for each array
    /*
    关于Array
    索引类型 : SizeType
    数组size : a.Size();
    */
    for(rapidjson::SizeType index = 0; index < array.Size(); ++index) {
        cout << "a[" << index << "] = " << array[index].GetInt() << endl;
    }

    // by iterator
    for (rapidjson::Value::ConstValueIterator it = array.Begin();
         it != array.End(); ++it) {
        cout << it->GetInt() << ' ';
    } cout << endl;

    // for each json
    for_each_json(document);

    rapidjson::StringBuffer SB;
    rapidjson::Writer writer(SB);
    document.Accept(writer);

    cout << SB.GetString() << endl;



    return 0;
}

void for_each_json(const rapidjson::Document &document)
{
    rapidjson::Value::ConstMemberIterator it;
    for (it = document.MemberBegin();
         it != document.MemberEnd(); ++it) {
        cout << it->name.GetString() << ": ";

        if (it->value.IsNull()) {
            cout << "null";
        }
        else if (it->value.IsString()) {
            cout << it->value.GetString();
            cout << "\tStringLength = " << it->value.GetStringLength();
        }
        else if (it->value.IsBool()) {
            cout << it->value.GetBool();
        }
        else if (it->value.IsInt()) {
            cout << it->value.GetInt();
        }
        else if (it->value.IsDouble()) {
            cout << it->value.GetDouble();
        }
        else if (it->value.IsArray()) { // 默认Int数组
            rapidjson::Value::ConstValueIterator val_it
                = it->value.Begin();
            for (; val_it != it->value.End(); ++val_it) {
                cout << val_it->GetInt() << ' ';
            }
        }
        else if (it->value.IsObject()) {
            ;
        }
        else {
            ;
        }

        cout << endl;
    }
}

Python json模块(很抱(qian)歉(zou),我是宇宙术)

使用Python内置的json模块

test.json
{
    "hello": "world",
    "t": true,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}
#!/usr/bin/python3

import json

if __name__ == '__main__':
    json_str = '''
    {
    "hello": "world",
    "t": true,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
    }
    '''

    # memory stream input
    data = json.loads(json_str)

    print(data)

    # memory stream output
    out_string = json.dumps(data, ensure_ascii=False, indent=2)
    print(out_string)

    # file stream input
    with open('test.json', 'r', encoding='utf-8') as input:
        data = json.load(input, encoding='utf-8')
        print(data)

    # file stream output
    with open('output.json', 'w', encoding='utf-8') as output:
        json.dump(data, output, ensure_ascii=False, indent=4)

    print('Done')

ujson版本(没什么变化)

#!/usr/bin/python3

import ujson
import json
"""
ujson

dump dumps

load loads

encode decode

"""

if __name__ == '__main__':
    json_str = '''
    {
        "name": "misaka",
        "age":14,
        "school": null
    }
    '''

    data = ujson.loads(json_str)
    print(data)

    with open('test.json', 'r', encoding='utf-8') as input:
        data = ujson.load(input)
        print(data)

    # ensure_ascii=False 输出的是utf-8
    result_str = ujson.dumps(data, indent=4, ensure_ascii=False)
    print(result_str)

    with open('output.json', 'w', encoding='utf-8') as output:
        ujson.dump(data, output, indent=4, ensure_ascii=False)

    print('Done')

你可能感兴趣的:(使用rapidjson Json解析)