pw_json#
Simple, efficient C++ JSON serialization
Stable C++17
Use pw::JsonBuilder to serialize JSON to a buffer. It’s simple, safe, and efficient.
pw::JsonBuffer<256> json_buffer;
pw::JsonObject& object = json_buffer.StartObject();
object.Add("tagline", "Easy, efficient JSON serialization!")
.Add("simple", is_simple)
.Add("safe", safety_percentage)
.Add("dynamic allocation", false);
pw::NestedJsonArray nested_array = object.AddNestedArray("features");
for (const std::string_view feature : features) {
nested_array.Append(feature);
}
The above code produces JSON equivalent to the following:
{
"tagline": "Easy, efficient JSON serialization!",
"simple": true,
"safe": 100,
"dynamic allocation": false,
"features": ["values", "arrays", "objects", "nesting!"]
}
JsonBuilder#
pw::JsonBuilder is used to create arbitrary JSON. It contains a JSON value, which may be an object or array. Arrays and objects may contain other values, objects, or arrays.
Example
// Declare a JsonBuffer (JsonBuilder with included buffer) and start a JSON
// object in it.
pw::JsonBuffer<128> json_buffer;
pw::JsonObject& json = json_buffer.StartObject();
const char* name = "Crag";
constexpr const char* kOccupationKey = "job";
// Add key-value pairs to a JSON object.
json.Add("name", name).Add(kOccupationKey, "hacker");
// Add an array as the value in a key-value pair.
pw::NestedJsonArray nested_array = json.AddNestedArray("skills");
// Append items to an array.
nested_array.Append(20).Append(1).Append(1).Append(1);
// Check that everything fit in the JSON buffer.
PW_ASSERT(json.ok());
// Compare the contents of the JSON to a std::string_view.
PW_ASSERT(std::string_view(json) ==
R"({"name": "Crag", "job": "hacker", "skills": [20, 1, 1, 1]})");
// Add an object as the value in a key-value pair.
pw::NestedJsonObject nested_object = json.AddNestedObject("items");
// Declare another JsonArray, and add it as nested value.
pw::JsonBuffer<10> inner_buffer;
inner_buffer.StartArray().Append(nullptr);
nested_object.Add("misc", inner_buffer);
// Add a value that is too large for the JsonBuffer.
json.Add("way too big!", huge_string_that_wont_fit);
// Adding the last entry failed, but the JSON is still valid.
PW_ASSERT(json.status().IsResourceExhausted());
PW_ASSERT(std::string_view(json) ==
R"({"name": "Crag", "job": "hacker", "skills": [20, 1, 1, 1],)"
R"( "items": {"misc": [null]}})");
API Reference#
Moved: pw_json