Skip to content

Writing JSON#

This page describes how to build and save JSON with aui::json. To save your own structures, see Custom types and JSON.

Building objects#

Assigning to operator[] of an empty AJson turns it into an object. Values can be numbers, booleans, strings, nullptr (a JSON null) or other AJsons.

1
2
3
4
5
6
AJson o;
o["name"] = "Alex2772";
o["year"] = 2020;
o["girlfriend"] = nullptr;

ASSERT_EQ(AJson::toString(o), R"({"name":"Alex2772","year":2020,"girlfriend":null})");

Objects keep the insertion order of their keys.

Assigning an AJson to a key nests it:

1
2
3
4
5
6
7
8
AJson o;
o["name"] = "Alex2772";
o["year"] = 2020;

AJson root;
root["user"] = o;

ASSERT_EQ(AJson::toString(root), R"({"user":{"name":"Alex2772","year":2020}})");

If the whole structure is known upfront, brace initialization is more compact:

AJson root = {
    {"array", AJson::Array{
        "value1",
        "value2",
    }},
    {"key", 1},
};

auto str = AJson::toString(root);
ASSERT_EQ(str, R"({"array":["value1","value2"],"key":1})");

Building arrays#

Use AJson::Array to create an array and push_back to append elements.

1
2
3
4
5
6
7
AJson root = AJson::Array{1, 2, 3};
ASSERT_EQ(AJson::toString(root), R"([1,2,3])");

root.push_back(10);
root.push_back(9);
ASSERT_EQ(AJson::toString(root), R"([1,2,3,10,9])");
ASSERT_EQ(root[1].asInt(), 2);

Producing text#

AJson::toString serializes the tree to a compact string, without whitespace between tokens. Strings are escaped automatically, and parsing the result with AJson::fromString yields the same tree back.

const char* str = R"({"a":null,"b":[1,2,3],"c":false,"d":true,"e":{"v":"123"}})";
ASSERT_EQ(AJson::toString(AJson::fromString(str)), str);