Rapidjson: How to convert rapidJson::Value to rapidJson::Document as root and write as json file?

Created on 11 Dec 2016  ·  4Comments  ·  Source: Tencent/rapidjson

My json file like:

[
    {
        "annotations": [
            {
                "class": "bbox",
                "height": 457.0,
                "id": "001",
                "type": "rect",
                "width": 336.0,
                "x": 97.0,
                "y": 60.0
            },
            {
                "class": "head",
                "height": 114.0,
                "id": "001",
                "type": "rect",
                "width": 208.0,
                "x": 222.0,
                "y": 65.0
            },
        ],
        "class": "image",
        "filename": "001.jpg"
    },
   {
        "annotations": [
            {
                "class": "bbox",
                "height": 406.0,
                "id": "001",
                "type": "rect",
                "width": 311.0,
                "x": 108.0,
                "y": 147.0
            },
            {
                "class": "head",
                "height": 107.0,
                "id": "001",
                "type": "rect",
                "width": 187.0,
                "x": 113.0,
                "y": 152.0
            },
        ],
        "class": "image",
        "filename": "002.jpg"
    },
]

I can get different object Value like:

Document d;
d.ParseStream(is);
for (SizeType i = 0; i < d.Size(); ++i) {
    const Value& o = d[i];
    ...
}

Now I want to create separate Document with every object o as root, and write these Documents as separate json files. How can I achieve this?
Thanks!

Most helpful comment

Each Value can be treated as a root of a DOM tree. And you can write any Value as JSON, by using v.Accept(writer).

The main addition from Value to Document is that Document contains an allocator for allocating Value.

If you really want to clone a Value to another Document, You can do that by:

~
Value& v = ...;
Document d;
d.CopyFrom(v, d.GetAllocator());
~

All 4 comments

Each Value can be treated as a root of a DOM tree. And you can write any Value as JSON, by using v.Accept(writer).

The main addition from Value to Document is that Document contains an allocator for allocating Value.

If you really want to clone a Value to another Document, You can do that by:

~
Value& v = ...;
Document d;
d.CopyFrom(v, d.GetAllocator());
~

Yes, it works.
By the way, I checked the content of the writing json file, there is no format for them. I mean there is no newline and indentation (like my question post). Is any way to add format control?

Use PrettyWriter instead.

Great, and thanks!

Was this page helpful?
0 / 5 - 0 ratings