Simpleson
|
Lightweight C++ JSON parser & serializer that is C++98 compatible with no dependencies
Simpleson is built under the following requirements:
A primary use case for simpleson is in an memory-constrained embedded system.
Simpleson was intentionally built such that a developer could simply copy json.h into the target project's inc
folder, copy json.cpp into the src
folder, and then compile the target project. No linking -> no drama.
Building the library and tests follows the standard build chain via CMake:
Unit tests can then be run by executing make test
The namespace of simpleson is simply json
. JSON objects can be parsed by calling json::jobject::parse()
, which takes a string and returns a jobject
. The array operators are overloaded for jobject
, meaning you can assign and access entries using the []
operators like many other software languages. Other useful methods of jobject
include:
has_key("key")
- Returns true if the key exists in the jobject
remove("key")
- Removes they entry associated with the key if the key exists in the jobject
clear()
- Removes all entries in the jobject
["key"].set_boolean(true)
- Sets the key to the boolean value["key"].set_null()
- Sets the value associated with the key to null["key"].is_true()
- Returns true if the boolean value associated with the key is true["key"].is_null()
- Returns true if the value associated with the key is nullpretty()
- Serializes the object into a "pretty" string (using tabs and newlines)An instance of jobject
can be searlized by casting it to a std::string
. Note that an instance of jobject
does not retain it's original formatting (it drops tabs, spaces outside strings, and newlines).
Simpleson supports arrays as the root object:
Arrays are stored in a jobject
. You can determine whether a jobject
is holding an array through the method is_array()
.
To access elements several levels down, the get(key)
and array(index)
can be used for objects and arrays, respectively:
Booleans are handled a bit differently than other data types. Since everything can be cast to a boolean, having an implicit boolean operator meant everything goes to a boolean! Instead, boolean values are set by using the set_boolean()
method. If you do not use this method and instead directly create/assign a boolean to a jobject
array entry, then the boolean will be cast to an int with a value of 0 or 1. Similarly, you can check if a value is set to true or false using the is_true()
method.