API Reference

The API of jsonpp is largely inspired by the ease of use of the Python json module. I considered the API of that module to be easy enough to use and understand in many ways but not in others. The goal of this library was to fix some of the issues with the json module and to allow the same ease of use in a C++ setting with static typing.

Error Handling

The parsing part of the library throws an error called parser_error.

class parser_error : public std::exception

The exception type used to report parsing errors.

parser_error(const std::string &str, unsigned line, unsigned column)

Constructs a parser error.

Parameters:
  • str – The error string.
  • line – The line the error occurred in.
  • column – The column the error occurred in.
const char *what() const noexcept

Returns the string representation of the error.

JSON Value

class value

The class that represents a JSON value according to the official JSON spec, ECMA-404.

Throughout the documentation of this class, there are six different types that the value class can hold:

  • null
  • object
  • array
  • string
  • boolean
  • number

It can only hold a single one of these types at a time.

value() noexcept
value(null) noexcept

Constructs a value with a null value.

Post condition:Internal type is null.
value(double val) noexcept

Constructs a value with the number value provided.

Post condition:Internal type is number.
value(bool b) noexcept

Constructs a value with the boolean value provided.

Post condition:Internal type is boolean.
value(const std::string &str)

Constructs a value with the string value provided.

Post condition:Internal type is string.
value(const array &arr)
value(std::initializer_list<value> l)

Constructs a value with the array value provided.

This allows you to use initializer lists to construct a value directly. e.g.

json::value x = { 1, 2, "hello", nullptr }; // OK
Post condition:Internal type is array.
value(const object &obj)

Constructs a value with the object value provided.

Post condition:Internal type is object.
value(const T &t)
value &operator=(const T &t)

Constructs a value from a serialisable type. The Internal type depends on the internal type of the resulting serialised object.

value(const value &other)
value &operator=(const value &other)

Copies one value to another value.

Post condition:The resulting internal type is the same as the other parameter.
value(value &&other) noexcept
value &operator=(value &&other) noexcept

Moves one value to another value. The ownership of the contents owned by other are transferred over.

Post condition:The resulting internal type is the same as the other parameter.
std::string type_name() const

Returns a string representation of the internal type.

Internal Type Returned String
array “array”
string “string”
object “object”
number “number”
boolean “boolean”
null “null”
void clear() noexcept

Deletes all internal storage being held.

Post condition:Internal type is null.
bool is<T>() const noexcept

Checks if the internal type is one of the C++ types provided.

Internal Type Valid C++ Types
array json::array
object json::object
null json::null
boolean bool
number All integral types such as int and float.
string const char* or std::string.

Anything else would return false but due to #10 a compiler error occurs instead.

T as<T>() const noexcept

Returns a copy of the internal value being held. For type equivalences, check the table for is<T>().

Similarly, an invalid type should throw an exception but due to #10 a compiler error is issued instead.

Note

This function uses the assert macro to check the preconditions.

Precondition:is<T>() must return true.
T as<T>(T &&default) const noexcept

Similar to as<T>() but if is<T>() is false, then the default value is returned.

value operator[](const std::string &str) const noexcept

Accesses the object at a given string key. If the value internal type is not json::object or the key is not found, then a value with an internal type of json::null is returned instead.

Example:

json::value x = json::object{
    { "key", 10 }, { "name", "bob" }
};

std::cout << x["key"].is<int>() << '\n'; // prints 1
value operator[](const Integral &index) const noexcept

Accesses the array at a given index. If the value internal type is not json::array or the index is out of bounds, then a value with an internal type of json::null is returned instead. Index starts at 0.

Example:

json::value x = { 1, 2, 3, 4, 5, 6 };
for(unsigned i = 0; i < 6; ++i) {
    std::cout << x[i].is<int>(); // prints 111111
}

Along with the value class, several type aliases are provided for other JSON types:

type null

Represents std::nullptr_t. For example, json::value x = nullptr; is valid.

type array

Represents std::vector<json::value>.

type object

Represents std::map<std::string, json::value>.

Parsing JSON

The API for parsing is composed of two functions and a class. The class does not have to actually be instantiated in the usual cases since the two free functions handle the creation of the parser for you.

class parser

Represents a JSON parser. This typically doesn’t need to be instantiated and you should use json::parse() instead.

The parser is not destructive and is implemented as a recursive descent parser.

parser(const char *str) noexcept

Creates a parser from a string already in memory. The lifetime of the string must be longer than the actual parser object. The string must be a valid JSON string or an exception will be thrown when parsing. The constructor does not parse anything – it just sets up the parser state.

void parse(value &val)

Parses the JSON string. If an error occurs during parsing then an error is thrown. Currently there are a couple of assumptions on the parsing state:

  • The internal string is UTF-8 encoded.
  • nan and inf are allowed.
  • Comments are disallowed currently. See #3.

The rest follows the ECMA-404 specification.

Throws:
  • parser_error – Thrown if a parsing error has occurred.
void parse(const std::string &str, value &val)

Parses a JSON string. Equivalent to constructing a parser and then using the parser::parse() function.

void parse(std::istream &in, value &val)

Retrieves the rdbuf of the std::istream to construct a string and parses the resulting string as JSON.

Dumping JSON

There’s an API in place to dump (i.e. serialise) C++ objects into JSON constructs.

class format_options

This class specifies the behaviour used when dumping JSON with the json::dump() interface.

enum flag_type : int

A regular enum (i.e. not an enum class) that specifies flags for use with the flags member.

enumerator none

The default value for flags. Specifies that no special formatting will occur.

enumerator allow_nan_inf

Allow nan and inf values to be printed in the resulting JSON. If this is not set and nan and inf are spotted, then “null” is printed instead.

enumerator minify

Minifies the resulting JSON by suppressing newlines from being printed and indentation.

enumerator escape_multi_byte

UTF-8 codepoints that are greater than 0x7F will be escaped into their proper UTF-16 codepoint with surrogate pairs included.

int flags

Specifies the special format behaviour for the family of json::dump() functions. Defaults to none.

int indent

Specifies how many spaces to indent when pretty printing the output. e.g. with an indent value of 4 then the JSON { "key": 10 } would be dumped as:

{
    "key": 10
}

Defaults to 4.

int precision

The default precision when printing number types. The default value is 6.

OStream &dump(OStream &out, const T &t, const format_options &options)

Dumps a C++ object to JSON with the specified options and a valid std::ostream instance such as std::cout or std::ofstream.

  • If the type is a string, then it will be printed as a string such as "Hello".
  • If the type is null, then it will print null.
  • If the type is an integral type, then it will print it with the specified precision of format_options::precision.
  • If the type is a container with begin and end defined then it will be printed as an array. The values of the array will be dumped recursively with json::dump().
  • If the type is a container with begin and end defined and has a pair-like value_type then it will be printed as an object. The key (i.e. p.first) will be dumped in accordance to json::key() while the value will be recursively called with json::dump().
  • If the type is value then it will print with the above in mind with its internal value.
void key(OStream &out, const T &t, const format_options &options)

Dumps the key type of object types. Only defined for integral types and strings.