Using the low-level parser

The following code snippet shows how to use the low-level json_parser class by providing an own handler class and passing it as a template argument:

#include <orcus/json_parser.hpp>
#include <cstring>
#include <iostream>

using namespace std;

class json_parser_handler : public orcus::json_handler
{
public:
    void object_key(std::string_view key, bool /*transient*/)
    {
        cout << "object key: " << key << endl;
    }

    void string(std::string_view val, bool /*transient*/)
    {
        cout << "string: " << val << endl;
    }

    void number(double val)
    {
        cout << "number: " << val << endl;
    }
};

int main()
{
    const char* test_code = "{\"key1\": [1,2,3,4,5], \"key2\": 12.3}";

    cout << "JSON string: " << test_code << endl;

    // Instantiate the parser with an own handler.
    json_parser_handler hdl;
    orcus::json_parser<json_parser_handler> parser(test_code, hdl);

    // Parse the string.
    parser.parse();

    return EXIT_SUCCESS;
}

The parser constructor expects the char array, its length, and the handler instance. The base handler class json_handler implements all required handler methods. By inheriting from it, you only need to implement the handler methods you need. In this example, we are only implementing the object_key(), string(), and number() methods to process object key values, string values and numeric values, respectively. Refer to the json_handler class definition for all available handler methods.

Executing this code will generate the following output:

JSON string: {"key1": [1,2,3,4,5], "key2": 12.3}
object key: key1
number: 1
number: 2
number: 3
number: 4
number: 5
object key: key2
number: 12.3