Skip to content
Adam Labranche edited this page Apr 10, 2015 · 7 revisions

This page contains some examples on how to use the JsonBox C++ library.

Create some JSON programmatically

Let's write some code to generate the following JSON:

{
    "menu": {
        "id": "file",
        "value": "File",
        "popup": {
            "menuitem": [
                {
                    "value": "New",
                    "onclick": "CreateNewDoc()"
                },
                {
                    "value": "Open",
                    "onclick": "OpenDoc()"
                },
                {
                    "value": "Close",
                    "onclick": "CloseDoc()"
                }
            ]
        }
    }
}

We could write this code:

#include <iostream>
#include <JsonBox.h>

using namespace JsonBox;

int main(int argc, char **argv) {
    Value root;

    root["menu"]["id"] = Value("file");
    root["menu"]["value"] = Value("File");
    root["menu"]["popup"]["menuitem"][2]["value"] = Value("Close");
    root["menu"]["popup"]["menuitem"][2]["onclick"] = Value("CloseDoc()");
    root["menu"]["popup"]["menuitem"][1]["value"] = Value("Open");
    root["menu"]["popup"]["menuitem"][1]["onclick"] = Value("OpenDoc()");
    root["menu"]["popup"]["menuitem"][size_t(0)]["value"] = Value("New");
    root["menu"]["popup"]["menuitem"][size_t(0)]["onclick"] = Value("CreateNewDoc()");
    
    std::cout << root;
    
    return 0;
}

If you look at the output, you'll notice the "value" member is not at the same place. This is because Objects are actually a std::map<std::string, JsonBox::Value>, so the order of the values depends on the sorting of the map (pretty much in alphabetical order for strings).

By the way, the reason why it's size_t(0) instead of simply 0 is because of an ambiguity with the other [] operator overloads for the std::string and the const char *.

Specifying the formatting options

In the previous example, the JSON was written to the console using std::cout directly. When writing a JSON value this way, the JSON will be indented. To write non-indented JSON, you need to use the writeToStream method and specify you do not want the output to be indented:

root.writeToStream(std::cout, false);

Reading a JSON file

Reading data from a JSON file is very simple. Let's say we have a file named "test.json" containing the following JSON:

{
    "employees" : [
        { "firstName" : "Angela", "lastName" : "Anaconda" },
        { "firstName" : "Robert", "lastName" : "Paulson" },
        { "firstName" : "Colin", "lastName" : "Mochrie" }
    ]
}

To load a JSON value from a file, you use the loadFromFile("test.json") member function.