ctl::json is a header-only JSON template library for C++.
json &operator=(const json &right) | (1) |
json &operator=(double right) | (2) |
json &operator=(bool right) | (3) |
json &operator=(const string_type &right) | (4) |
json &operator=(const char_type *right) | (5) |
template <typename StringType> StringType stringify() const |
(1) |
template <typename StringType> StringType to_string() const |
(2) |
string_type to_string() const | (3) |
string_type stringify() const | (4) |
template <typename NumType> NumType num() const |
(1) |
double num() const | (2) |
json &set_str(const string_type &s) | (1) |
json &set_str(const char_type *const p) | (2) |
template <typename InputIterator> json &set_str(InputIterator begin, const InputIterator end) |
(3) |
const json &operator[](const std::size_t no) const | (1) |
json &operator[](const std::size_t no) | (2) |
const json &operator[](const string_type &key) const | (1) |
json &operator[](const string_type &key) | (2) |
ctl::json is a C++ json library. Features are as follows:
The oldest compiler on where I confirm ctl::json can be used is Visual C++ 2005 in Visual Studio 2005.
Place ctljson.hpp
somewhere in your PATH and include it.
Create an instance of the ctl::json
type, and pass a JSON data string (std::string
or null-terminated string) to its member function, ctl::json::parse()
:
// Example 01: ctl::json root; const std::string jsondata = R"({ "a": 1, "b": { "b1": "#", "b2": "%" } })"; root.parse(jsondata); // Reads and parses JSON data. printf(R"(["a"] = %d, ["b"]["b1"] = "%s")" "\n", root["a"].num<int>(), root["b"]["b1"].str().c_str()); // Output: // ["a"] = 1, ["b"]["b1"] = "#"
Reading can be performed also by passing a JSON data string to the constructor:
// Example 02: ctl::json root(R"({ "c": 2, "d": { "d1": "##", "d2": "%%" } })"); printf(R"(["c"] = %d, ["d"]["d2"] = "%s")" "\n", root["c"].num<int>(), root["d"]["d2"].str().c_str()); // Output: // ["c"] = 2, ["d"]["d2"] = "%%"
The member function stringify()
or to_string()
of the ctl::json
type returns an instance of std::string
that contains a JSON data.
There is no difference in behaviour between these two member functions, only the names are different. The former is a JavaScript-derived name, and the latter is a C++-ish name.
// Example 03: ctl::json root, childnode; childnode(0) = "zero"; childnode(1) = "one"; root("obj") = childnode; root("str") = "ABC"; const std::string jsondata = root.stringify(); // Outputs JSON data. // const auto jsondata = root.stringify<std::string>(); // Returned type can be specified explicitly by template argument. printf("%s\n", jsondata.c_str()); // Output: // {"obj":["zero","one"],"str":"ABC"}
This library provides the four types, ctl::json
, ctl::wjson
, ctl::u16json
, ctl::u8json
.
Their usage is basically the same, except that they use different types to hold a string.
On behalf of them, how to use ctl::json
is explained in the following.
An instance of ctl::json
can store a value of one of the types defined in RFC 8259, number, string, array, object (name-keyed array), or three literal names, true
, false
, or null
.
And each element in an array or object is also an instance of ctl::json
.
The member function type()
can be used to check which type an instance currently stores.
The return value of this function is an integer of enum type ctl::json::value_type
, consisting of the following constant values:
number
, string
, array
, object
, boolean
(only true
or false
can be stored), null
, unassigned
, fallback
.
Ways to access to each type are as follows.
For the ctl::json
type, char_type
and string_type
in the explanation below are typedef
s of char
and std::string
respectively (For the other types, see the Types section):
Reading | template <typename NumType> double num() const string_type numstr() const
|
---|---|
Writing | ctl::json &operator=(double) ctl::json &operator=(bool) ctl::json &set_num(double, int precision)
|
ECMAScript (JavaScript) stores numbers in the IEEE 754 64-bit format.
So, this library also stores a numerical value in the double
type.
To simplify implementation, overload functions for various integer types are intentionally not provided.
You can get a number as a numerical value by calling the member function num()
, such as js.num<int>()
. If the template argument is omitted, the value of the double
type is returned.
As the mantissa part of IEEE 754 64-bit format is 53 bits, trying to read or write a interger with a greater number of more than 53 bits is not safe but would cause a precision error. This is a specification originated from ECMAScript.
Furthermore, precision errors may also occur if your compiler's double
type is not based on IEEE 754.
In situations where strict precision is required, it is recommended to read and write a number as a string (like js = "12.34" instead of js = 12.34).
In writing with operator=()
, decimals after the decimal point are rounded to 6 digits, trailing zeros are removed, and if there are no digits are left after the decimal point, the decimal point itself is also removed.
To change the rounding precision after the decimal point and/or to keep trailing zeros, you can use set_num()
explained later.
Reading | string_type str() const
|
---|---|
Writing | ctl::json &operator=(const string_type &) ctl::json &operator=(const char_type *) ctl::json &set_str(const string_type &) ctl::json &set_str(const char_type *) template <typename InputIterator> ctl::json &set_str(InputIterator begin, const InputIterator end) |
ctl::json
, ctl::u8json
: a passed string is interpreted as UTF-8.
ctl::wjson
, ctl::u16json
: a passed string is interpreted as UTF-16.
[Until 2.102] The name of set_str()
was raw()
. In assignment by operator=()
, characters in the copied string is all unescaped,
while in assignment by raw()
, the passed string becomes the instance value as is.
For example, while js = "\\u0026"
sets js
's value to "&"
, js.raw("\\u0026")
sets the value to "\u0026"
Reading | bool is_true() const bool is_false() const string_type numstr() const
|
---|---|
Writing | ctl::json &operator=(bool) ctl::json &set_bool(const bool)
|
is_true()
returns true
when the instance is of the boolean type and its value is true
.
is_false()
returns true
when the instance is of the boolean type and its value is false
.
numstr()
returns the instance's value as a string "true"
or "false"
if the instance is of the boolean type.
Reading | bool is_null() const string_type numstr() const
|
---|---|
Writing | ctl::json &set_null()
|
is_null()
returns true
if the instance is null.
numstr()
returns a string "null"
if the instance is null.
Reading | ctl::json &operator[](const std::size_t pos) ctl::json &operator()(const std::size_t pos) |
---|---|
Writing | ctl::json &operator[](const std::size_t pos) ctl::json &operator()(const std::size_t pos) |
Addition | void push_back(const ctl::json &newnode)
|
Insert | bool insert(const std::size_t pos, ctl::json &newnode)
|
Remove | bool erase(const std::size_t pos)
|
Get number of elements | std::size_t size() const
|
A value of each element in an array is itself an instance of ctl::json
. Therefore, for example, "the second data of the first element" can be accessed with js[1][2]
.
The difference between writing like js[0]
and writing like js(0)
is explained later.
Reading | ctl::json &operator[](const string_type &key) ctl::json &operator()(const string_type &key) |
---|---|
Writing | ctl::json &operator[](const string_type &key) ctl::json &operator()(const string_type &key) |
Addition | void push_back(const ctl::json &newnode)
|
Insert | bool insert(const string_type &pos, const string_type &key, ctl::json &newnode)
|
Remove | bool erase(const string_type &key)
|
Get number of elements | std::size_t size() const
|
While the array type uses a numeric value as an index, the object type uses a string as an index key.
Depending on the programming language, this type is also called a "associative array" or "dictionary".
It is the same as the array type except that the index is a string.
The difference between writing like js["key"]
and js("key")
is explained later.
Writing data of a type different from the type a target instance currently stores does not cause an error, but simply the instance's type information will be overwritten accordingly.
For arrays and objects, there are two ways to access their elements:
operator()()
:
Always returns a reference to an actually existing element. For an array, if an index value n
passed as an argument is equal to or greater than the array size, first the size of the array is expanded to n+1
then returnes a reference to the element at [n]
; for an object, if a key name passed as an argument does not in the object, first a new element whose name is n
is created then returns a reference to it.
operator[]()
:
If the element specified by the index value or key name already exists, returns a reference to it.
If it does not exist, returns a reference to the special element, "the fallback node", without creating any new element.
This access way guarantees not to change the current tree structure of JSON data.
The fallback node is a special node that is returned when the element specified by the index value or key name does not exist.
The fallback node is returned only when operator[]()
is used to access a value.
// Example 04: ctl::json root(R"({ "a": 1, "b": 2 })"); printf(R"(root["c"] = %d, root("d") = %d)" "\n", root["c"].num<int>(), root("d").num<int>()); // Accessing ["c"] and ("d") that do not exist in root. const std::string jsondata = root.stringify(); // Exports JSON data. printf("%s\n", jsondata.c_str()); // Output: // root["c"] = 0, root("d") = 0 // {"a":1,"b":2,"d":null}
In Example 04 above, access to root["c"]
using operator[]()
did not cause creation of any new element, whereas access to root("d")
using operator()()
caused creation of a new element (The reason why its value is null
is because no assignment has been done for the newly created element).
Whether an element is an actually existing element or the fallback node can be checked by calling member function exists()
(which returns true
if a real element) or is_fallback()
(which returns true
if the fallback node).
// Example 05: ctl::json root(R"({ "a": 1 })"); printf(R"(["a"] = %d/%d)" "\n", root["a"].exists(), // Can be written also as root.exists("a") root["a"].is_fallback()); printf(R"(["b"] = %d/%d)" "\n", root["b"].exists(), root["b"].is_fallback()); // Output: // ["a"] = 1/0 // ["b"] = 0/1
All descendants of the fallback node are fallback nodes.
operator[]()
allows you to access data in a deep tree without worrying that the tree structure will be changed inadvertently.
// Example 06: ctl::json root(R"({ "a": 1 })"); printf(R"(["a"]["b"]["c"] = %d/%d)" "\n", root["a"]["b"]["c"].exists(), root["a"]["b"]["c"].is_fallback()); // Output: // ["a"]["b"]["c"] = 0/1
It is not possible to assign a value to the fallback node.
Making it an lvalue does not result in an error, but it is simply ignored.
And also, trying creation of a new element by using operator()()
beneath the fallback node will be ignored.
// Example 07: ctl::json root(R"({ "a": 1 })"); root["a"]["b"]("c") = 2; // Trying creating ("c") under non-existing ["b"] printf(R"(["a"]["b"]("c") = %d/%d %d)" "\n", root["a"]["b"]("c").exists(), root["a"]["b"]("c").num<int>(), root["a"].num<int>()); // Output: // ["a"]["b"]("c") = 0/0 1 // The value of ["a"] remains 1. Not changed to the object type.
The full list of member functions of ctl::json
, ctl::wjson
, ctl::u16json
, and ctl::u8json
class.
The following types are defined.
char_type | string_type | Note | |
---|---|---|---|
ctl::json | typedef of char |
typedef of std::u8string |
|
ctl::u8json | typedef of std::string |
typedef of char8_t |
Only C++20 and later. |
ctl::wjson | typedef wchar_t |
typedef std::wstring |
Defined only if 0xffff <= WCHAR_MAX < 0x110000. |
ctl::u16json | typedef of char16_t |
typedef of std::u16string |
Only C++11 and later. |
string_type
s in ctl::json
and ctl::u8json
hold a UTF-8 sequence.
string_type
s in ctl::wjson
and ctl::u16json
hold a UTF-16 sequence.
As mentioned in the table above, ctl::wjson
is defined only if WCHAR_MAX
is equal to or more than 0xFFFF and less than 0x110000.
Virtually, it is provided for Windows.
The folowing values are defined to represent the type of data stored by an instance:
enum value_type { // Since version 2.109. array, object, number, string, boolean, null, unassigned, fallback // Until version 2.108. null, boolean, number, string, array, object, unassigned, fallback };
The return value of member function type() is this type.
boolean
is a type that can store a true
or false
value.
The last two types are defined for internal use.
An instance created with the constructor that takes no argument is of the unassigned
type.
There are four types as public
ones: 1) creates an empty instance, 2) copies from another instance, 3) receives and parses a string, and 4) receives and parses a [begin, end) pair.
json(); | (1) |
json(const json &right); | (2) |
template <typename StringType> explicit json(const StringType &s); |
(3) |
template <typename ForwardIterator> json(ForwardIterator begin, ForwardIterator end); |
(4) |
In addition, there exists the fourth one as a private
member for creating the fallback node.
Since version 2.106, the parameter type of the third one is not string_type
, so any string type can be passed to it. The passed sequence is always interpreted as a UTF-8 sequence.
Clears the current value and sets the type of the instance to unassigned
.
Returns the value type. It is an integer of enum value_type.
Returns true
if the stored value is of the number type; otherwise returns false
.
Returns true
if the stored value is of the string type; otherwise returns false
.
Returns true
if the stored value is of the boolean type; otherwise returns false
.
Returns true
if the stored value is of the boolean type and true
; otherwise returns false
.
Returns true
if the stored value is of the boolean type and false
; otherwise reutrns false
.
Returns true
if the stored value is null
.
Returns true
if the instance has an array; otherwise returns false
.
Returns true
if the instance has an object; otherwise returns false
.
Returns true
if the instance is the fallback node; otherwise returns false
.
Returns true
if the instance has any valid value; otherwise returns false
.
false
is returned when
1) nothing has been assigned since the instance was created,
2) clear()
is called,
3) the previous parsing has failed, or
4) the instances is the fallback node.
Returns true
if the instance is not the fallback node but a real element; otherwise returns false
.
When the instance is of the array type and no < size()
, returns true
.
Otherwise returns false
.
When the instance is of the object type and the element whose index name is key
exists, returns true
.
Otherwise returns false
.
json &operator=(const json &right) | (1) |
json &operator=(double right) | (2) |
json &operator=(bool right) | (3) |
json &operator=(const string_type &right) | (4) |
json &operator=(const char_type *right) | (5) |
These copy rvalue right
to self (lvalue).
When assigning from a numeric value, the numeric value is stored along with a string representation that has been converted from the value as if a printf
family function is called with arguments ("%.6f", value)
. If the numeric value is a decimal, trailing zeros after the decimal point are removed from the resulting string, and when there are no digits are left after the decimal point, the decimal point itself is also removed.
This "stringified numeric value" is used when the value is output by member function stringify()
or to_string
.
For changing the rounding precision after the decimal point and/or keeping trailing zeros, you can use member function set_num()
.
[Until 2.102] When assigning from a string, all escaped characters (\" \t \n etc.) in the string are unescaped during copying.
template <typename StringType> bool parse(const StringType &s) |
(1) |
template <typename CharType> bool parse(const CharType *p) |
(2) |
template <typename ForwardIterator> ForwardIterator parse(ForwardIterator begin, ForwardIterator end) |
(3) |
These parse string s
, null-terminated string p
, or character sequence [begin, end)
, as JSON data encoded in UTF-8.
The first two will return true
if parsing has successfully completed its run.
string_type
, char_type
respectively, so any string type can be passed to them.
The last one that takes a pair of iterators as parameters will return the iterator at the point when parsing is finished or stopped.
If the returned iterator is equal to end
and is_assigned()
returns true
, it means that the parsing has been successfully completed.
If is_assigned()
returns false
with all the returned iterator being equal to end
, then it means that an opening "
, [
, or {
was found but the corresponding closing "
, ]
, or }
was not found through the parsing.
During parsing, all escaped characters (such as \" \t \n) in the string are unescaped.
Except for this point, the parsers of ctl::json
and ctl::u8json
do not interpret the input string. Even an input string contains a sequence being invalid as UTF-8, it is parsed and stored as is.
The parsers of ctl::wjson
and ctl::u16json
break off parsing if any sequence that cannot be converted to UTF-16 is found.
template <typename StringType> StringType stringify() const |
(1) |
template <typename StringType> StringType to_string() const |
(2) |
string_type stringify() const | (3) |
string_type to_string() const | (4) |
These output the value of the instance as JSON data encoded in UTF-8.
During exporting, characters that cannot be output as is, such as "
and \
, are escaped.
There is no difference in behaviour between stringify()
and to_string()
, only the names are different. The former is a JavaScript-derived name, and the latter is a C++-ish name.
The fallback node and instances with type json::unassigned
are all translated to null
.
Since version 2.106 the return type can be specified by the first template argument. If omitted, a string of string_type
is returned..
template <typename NumType> NumType num() const |
(1) |
double num() const | (2) |
When type() == json::number
, returns the stored value as a numeric value.
When type() == json::boolean
and the stored value is true
, then returns 1.0
.
Otherwise returns 0.0
.
Since version 2.108 the return type can be specified by the template argument. If omitted, a value of the double
type is returned.
When type() == json::number
, the stored value is returned as a string.
When type() == json::boolean
, if the stored value is true
returns literal string "true"
, otherwise returns string literal "false"
.
When type() == json::null
returns literal string "null"
.
When type()
is not any type above, returns an empty string.
For all data types to be converted to a string, you can use stringify()
/ to_string()
above.
When type() == json::string
returns the stored string.
Othewise return an empty string.
When precision
is a positive number, conversion as if a printf
family function is called with arguments ("%.*f", precision, d)
is performed and both the resulting string and the original numeric value d
are stored in the instance.
When precision
is a negative number, the precision
value is first converted to an absolute value and the conversion described above is performed. Then, in addition, if the value d
is a decimal, trailing zeros after the decimal point are removed, and when there are no digits are left after the decimal point, the point itself is also removed.
This "stringified numeric value" is used when the value is output by member function stringify()
or to_string
.
Incidentally, operator=(double d)
above calls set_num(d, -6)
.
json &set_str(const string_type &s) | (1) |
json &set_str(const char_type *const p) | (2) |
template <typename InputIterator> json &set_str(InputIterator begin, const InputIterator end) |
(3) |
These copy string s
, null-terminated string p
, or character sequence [begin, end)
, to self (lvalue), with treating as a UTF-8 string.
[Until 2.102] The name of these functions was raw()
. Unlike operator=(const string_type &)
that unescaped characters in the string during copying, these functions did not unescape.
When the instance is of the array (json::array
) or object (json::object
) type, returns the current number of elements.
Otherwise returns 0.
const json &operator[](const std::size_t no) const | (1) |
json &operator[](const std::size_t no) | (2) |
If the instance is of the array and no < size()
,
returns a reference to (*this)[no]
.
Otherwise returns a reference to the fallback node.
const json &operator[](const string_type &key) const | (1) |
json &operator[](const string_type &key) | (2) |
If the instance is of the object type and the element whose index name is key
exists, returns a reference to it.
Otherwise returns a reference to the fallback node.
If the instance is of the array type, returns a reference to (*this)[no]
.
When no >= size()
, the size of the array is first expanded to no + 1
and returns a reference to (*this)[no]
.
If the current stored value is not of the array type, the above process is performed after the type is changed to the array type.
If the instance is of the object type, returns a reference to (*this)[key]
.
When an element whose index name is key
does not exist, it is created and returns a reference to it. And the name key
is added to the object's internal order list.
If the current stored value is not of the object type, the above process is performed after the type is changed to the object type.
If the instance is of the array type and no < size()
, removes (*this)[no]
.
If the instance is of the object type, removes (*this)[key]
.
If the instance is of the array type and no <= size()
, insert right
jsut before (*this)[no]
.
If the instance is of the object type, creates a new element whose index name is key
just before (*this)[pos]
and copies right
to it.
If an element whose index name is key
already exists in the object, it is first removed and the above preocess is performed.
When an element whose index name is pos
does not exist, no operation is performed.
If the instance is of the array type, adds right
after the end of the array.
If the instance is of the object type, adds right
with the index name key
as the last element of the object.
If any element whose name is key
already exists, the element is replaced with right
and its order is moved to the last.
For adding a new element to an object, using of assigment via operator()() is recommended rather than using this function; because this push_back()
is a bit slow for ensuring that the element whose index name is key
is placed at the last in the object's internal order list.
Set the type of the instance to boolean
, and the value to b
.
Set the type and value of the instance to null
.
There is no exception specific to this library. Only std::bad_alloc
is thrown when new
is failed internally.
The default namespace
of this library is ctl
, but you can change it with any name you like by defining NAMESPACE_CTLJSON
in advance, like #define NAMESPACE_CTLJSON othername
.