libjson Simple Write Example

This example uses the C interface to create a set of JSON nodes that you can then dump to a string and use however you like.

JSONNode n(JSON_NODE);
n.push_back(JSONNode("String Node", "String Value"));
n.push_back(JSONNode("Integer Node", 42));
n.push_back(JSONNode("Floating Point Node", 3.14));
n.push_back(JSONNode("Boolean Node", true));
std::string jc = n.write_formatted();
std::cout << jc << std::endl;

The result will look like this:

{
    "String Node" : "String Value",
    "Integer Node" : 42,
    "Floating Point Node" : 3.14,
    "Boolean Node" : true
}

The first line generates a new root node for us to work with. This node will contain the entire JSON structure we want to create.

Line 2 creates a new JSON_STRING node, i.e. a node that will have a string value, and attaches the new node to the end of our original root node n.

Line 3, 4 and 5 create and add new integer, floating point and boolean nodes respctively and add them to the root node. Both the integer and floating point methods will create JSON_NUMBER nodes where the numeric values will be printed to a JSON string without any quotation marks. The boolean method will take a true or a false and print a "true" or "false" in the final JSON string.

Line 6 returns a json_string that contains nicely formatted JSON code from the structure we just created. The string will be nicely tabbed and returned for human readability. Use this for debugging purposes. If you are going into production, use the write method instead which will compact the JSON into a single line that saves space for transmission over the Net or between components.