WPILibC++  unspecified
wpi::json Class Reference

a class to store JSON values More...

#include <json.h>

Classes

class  binary_writer
 serialization to CBOR and MessagePack values More...
 
class  iter_impl
 a template for a random access iterator for the json class More...
 
class  json_pointer
 JSON Pointer. More...
 
union  json_value
 a JSON value More...
 
class  parser
 syntax analysis More...
 
class  serializer
 wrapper around the serialization functions More...
 

Public Types

enum  parse_event_t : uint8_t {
  parse_event_t::object_start, parse_event_t::object_end, parse_event_t::array_start, parse_event_t::array_end,
  parse_event_t::key, parse_event_t::value
}
 JSON callback events. More...
 
using value_t = detail::value_t
 
using parser_callback_t = std::function< bool(int depth, parse_event_t event, json &parsed)>
 per-element parser callback type More...
 

Public Member Functions

std::string type_name () const
 return the type as string More...
 

Static Public Member Functions

static json meta ()
 returns version information on the library More...
 

Friends

template<detail::value_t >
struct detail::external_constructor
 
class JsonTest
 

exceptions

Classes to implement user-defined exceptions.

using exception = detail::exception
 general exception of the json class More...
 
using parse_error = detail::parse_error
 exception indicating a parse error More...
 
using invalid_iterator = detail::invalid_iterator
 exception indicating errors with iterators More...
 
using type_error = detail::type_error
 exception indicating executing a member function with a wrong type More...
 
using out_of_range = detail::out_of_range
 exception indicating access out of the defined range More...
 
using other_error = detail::other_error
 exception indicating other errors More...
 

container types

The canonic container types to use json like any other STL container.

using value_type = json
 the type of elements in a json container
 
using reference = value_type &
 the type of an element reference
 
using const_reference = const value_type &
 the type of an element const reference
 
using difference_type = std::ptrdiff_t
 a type to represent differences between iterators
 
using size_type = std::size_t
 a type to represent container sizes
 
using pointer = json *
 the type of an element pointer
 
using const_pointer = const json *
 the type of an element const pointer
 
using iterator = iter_impl< json >
 an iterator for a json container
 
using const_iterator = iter_impl< const json >
 a const iterator for a json container
 

JSON value data types

The data types to store a JSON value.

These types are derived from the template arguments passed to class json.

using object_t = llvm::StringMap< json >
 a type for an object More...
 
using array_t = std::vector< json >
 a type for an array More...
 
using string_t = std::string
 a type for a string More...
 
using boolean_t = bool
 a type for a boolean More...
 
using number_integer_t = int64_t
 a type for a number (integer) More...
 
using number_unsigned_t = uint64_t
 a type for a number (unsigned) More...
 
using number_float_t = double
 a type for a number (floating-point) More...
 

constructors and destructors

Constructors of class json, copy/move constructor, copy assignment, static functions creating objects, and the destructor.

static json array (std::initializer_list< json > init=std::initializer_list< json >())
 explicitly create an array from an initializer list More...
 
static json object (std::initializer_list< json > init=std::initializer_list< json >())
 explicitly create an object from an initializer list More...
 
 json (const value_t value_type)
 create an empty value with a given type More...
 
 json (std::nullptr_t=nullptr) noexcept
 create a null object More...
 
template<typename CompatibleType , typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t<!std::is_base_of< wpi::raw_istream, U >::value &&!std::is_same< U, json >::value &&!detail::is_json_nested_type< json, U >::value, int > = 0>
 json (CompatibleType &&val)
 create a JSON value More...
 
 json (std::initializer_list< json > init, bool type_deduction=true, value_t manual_type=value_t::array)
 create a container (array or object) from an initializer list More...
 
 json (size_type cnt, const json &val)
 construct an array with count copies of given value More...
 
template<class InputIT , typename std::enable_if< std::is_same< InputIT, json::iterator >::value||std::is_same< InputIT, json::const_iterator >::value, int >::type = 0>
 json (InputIT first, InputIT last)
 construct a JSON container given an iterator range More...
 
 json (const json &other)
 copy constructor More...
 
 json (json &&other) noexcept
 move constructor More...
 
referenceoperator= (json other) noexcept(std::is_nothrow_move_constructible< value_t >::value &&std::is_nothrow_move_assignable< value_t >::value &&std::is_nothrow_move_constructible< json_value >::value &&std::is_nothrow_move_assignable< json_value >::value)
 copy assignment More...
 
 ~json ()
 destructor More...
 

object inspection

Functions to inspect the type of a JSON value.

std::string dump (const int indent=-1) const
 serialization More...
 
void dump (llvm::raw_ostream &os, int indent=-1) const
 serialization More...
 
value_t type () const noexcept
 return the type of the JSON value (explicit) More...
 
bool is_primitive () const noexcept
 return whether type is primitive More...
 
bool is_structured () const noexcept
 return whether type is structured More...
 
bool is_null () const noexcept
 return whether value is null More...
 
bool is_boolean () const noexcept
 return whether value is a boolean More...
 
bool is_number () const noexcept
 return whether value is a number More...
 
bool is_number_integer () const noexcept
 return whether value is an integer number More...
 
bool is_number_unsigned () const noexcept
 return whether value is an unsigned integer number More...
 
bool is_number_float () const noexcept
 return whether value is a floating-point number More...
 
bool is_object () const noexcept
 return whether value is an object More...
 
bool is_array () const noexcept
 return whether value is an array More...
 
bool is_string () const noexcept
 return whether value is a string More...
 
bool is_discarded () const noexcept
 return whether value is discarded More...
 
 operator value_t () const noexcept
 return the type of the JSON value (implicit) More...
 

value access

Direct access to the stored value of a JSON value.

template<typename BasicJsonType , detail::enable_if_t< std::is_same< typename std::remove_const< BasicJsonType >::type, json >::value, int > = 0>
json get () const
 get special-case overload More...
 
template<typename ValueTypeCV , typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t< !std::is_same< json, ValueType >::value, int > = 0>
ValueType get () const
 get a value (explicit) More...
 
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
PointerType get () noexcept
 get a pointer value (explicit) More...
 
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
const PointerType get () const noexcept
 get a pointer value (explicit) More...
 
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
PointerType get_ptr () noexcept
 get a pointer value (implicit) More...
 
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value &&std::is_const< typename std::remove_pointer< PointerType >::type >::value, int >::type = 0>
const PointerType get_ptr () const noexcept
 get a pointer value (implicit) More...
 
template<typename ReferenceType , typename std::enable_if< std::is_reference< ReferenceType >::value, int >::type = 0>
ReferenceType get_ref ()
 get a reference value (implicit) More...
 
template<typename ReferenceType , typename std::enable_if< std::is_reference< ReferenceType >::value &&std::is_const< typename std::remove_reference< ReferenceType >::type >::value, int >::type = 0>
ReferenceType get_ref () const
 get a reference value (implicit) More...
 
template<typename ValueType , typename std::enable_if< !std::is_pointer< ValueType >::value &&!std::is_same< ValueType, std::string::value_type >::value &&!std::is_same< ValueType, std::initializer_list< std::string::value_type >>::value, int >::type = 0>
 operator ValueType () const
 get a value (implicit) More...
 

element access

Access to the JSON value.

reference at (size_type idx)
 access specified array element with bounds checking More...
 
const_reference at (size_type idx) const
 access specified array element with bounds checking More...
 
reference at (llvm::StringRef key)
 access specified object element with bounds checking More...
 
const_reference at (llvm::StringRef key) const
 access specified object element with bounds checking More...
 
reference operator[] (size_type idx)
 access specified array element More...
 
const_reference operator[] (size_type idx) const
 access specified array element More...
 
reference operator[] (llvm::StringRef key)
 access specified object element More...
 
const_reference operator[] (llvm::StringRef key) const
 read-only access specified object element More...
 
template<typename T , std::size_t n>
reference operator[] (T *(&key)[n])
 access specified object element More...
 
template<typename T , std::size_t n>
const_reference operator[] (T *(&key)[n]) const
 read-only access specified object element More...
 
template<typename T >
reference operator[] (T *key)
 access specified object element More...
 
template<typename T >
const_reference operator[] (T *key) const
 read-only access specified object element More...
 
template<class ValueType , typename std::enable_if< std::is_convertible< json, ValueType >::value, int >::type = 0>
ValueType value (llvm::StringRef key, ValueType default_value) const
 access specified object element with default value More...
 
std::string value (llvm::StringRef key, const char *default_value) const
 overload for a default value of type const char* More...
 
template<class ValueType , typename std::enable_if< std::is_convertible< json, ValueType >::value, int >::type = 0>
ValueType value (const json_pointer &ptr, ValueType default_value) const
 access specified object element via JSON Pointer with default value More...
 
std::string value (const json_pointer &ptr, const char *default_value) const
 overload for a default value of type const char* More...
 
reference front ()
 access the first element More...
 
const_reference front () const
 access the first element More...
 
reference back ()
 access the last element More...
 
const_reference back () const
 access the last element More...
 
template<class IteratorType , typename std::enable_if< std::is_same< IteratorType, json::iterator >::value||std::is_same< IteratorType, json::const_iterator >::value, int >::type = 0>
void erase (IteratorType pos)
 remove element given an iterator More...
 
template<class IteratorType , typename std::enable_if< std::is_same< IteratorType, json::iterator >::value||std::is_same< IteratorType, json::const_iterator >::value, int >::type = 0>
void erase (IteratorType first, IteratorType last)
 remove elements given an iterator range More...
 
size_type erase (llvm::StringRef key)
 remove element from a JSON object given a key More...
 
void erase (const size_type idx)
 remove element from a JSON array given an index More...
 

lookup

iterator find (llvm::StringRef key)
 find an element in a JSON object More...
 
const_iterator find (llvm::StringRef key) const
 find an element in a JSON object More...
 
size_type count (llvm::StringRef key) const
 returns the number of occurrences of a key in a JSON object More...
 

iterators

static iteration_proxy< iteratoriterator_wrapper (reference cont)
 wrapper to access iterator member functions in range-based for More...
 
static iteration_proxy< const_iteratoriterator_wrapper (const_reference cont)
 wrapper to access iterator member functions in range-based for More...
 
iterator begin () noexcept
 returns an iterator to the first element More...
 
const_iterator begin () const noexcept
 returns a const iterator to the first element More...
 
const_iterator cbegin () const noexcept
 returns a const iterator to the first element More...
 
iterator end () noexcept
 returns an iterator to one past the last element More...
 
const_iterator end () const noexcept
 returns a const iterator to one past the last element More...
 
const_iterator cend () const noexcept
 returns a const iterator to one past the last element More...
 

capacity

bool empty () const noexcept
 checks whether the container is empty More...
 
size_type size () const noexcept
 returns the number of elements More...
 
size_type max_size () const noexcept
 returns the maximum possible number of elements More...
 

modifiers

void clear () noexcept
 clears the contents More...
 
void push_back (json &&val)
 add an object to an array More...
 
reference operator+= (json &&val)
 add an object to an array More...
 
void push_back (const json &val)
 add an object to an array More...
 
reference operator+= (const json &val)
 add an object to an array More...
 
void push_back (const std::pair< llvm::StringRef, json > &val)
 add an object to an object More...
 
reference operator+= (const std::pair< llvm::StringRef, json > &val)
 add an object to an object More...
 
void push_back (std::initializer_list< json > init)
 add an object to an object More...
 
reference operator+= (std::initializer_list< json > init)
 add an object to an object More...
 
template<class... Args>
void emplace_back (Args &&...args)
 add an object to an array More...
 
template<class... Args>
std::pair< iterator, bool > emplace (llvm::StringRef key, Args &&...args)
 add an object to an object if key does not exist More...
 
iterator insert (const_iterator pos, const json &val)
 inserts element More...
 
iterator insert (const_iterator pos, json &&val)
 inserts element More...
 
iterator insert (const_iterator pos, size_type cnt, const json &val)
 inserts elements More...
 
iterator insert (const_iterator pos, const_iterator first, const_iterator last)
 inserts elements More...
 
iterator insert (const_iterator pos, std::initializer_list< json > ilist)
 inserts elements More...
 
void insert (const_iterator first, const_iterator last)
 inserts elements More...
 
void swap (reference other) noexcept(std::is_nothrow_move_constructible< value_t >::value &&std::is_nothrow_move_assignable< value_t >::value &&std::is_nothrow_move_constructible< json_value >::value &&std::is_nothrow_move_assignable< json_value >::value)
 exchanges the values More...
 
void swap (array_t &other)
 exchanges the values More...
 
void swap (object_t &other)
 exchanges the values More...
 
void swap (std::string &other)
 exchanges the values More...
 

lexicographical comparison operators

bool operator== (const_reference lhs, const_reference rhs) noexcept
 comparison: equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator== (const_reference lhs, const ScalarType rhs) noexcept
 comparison: equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator== (const ScalarType lhs, const_reference rhs) noexcept
 comparison: equal More...
 
bool operator!= (const_reference lhs, const_reference rhs) noexcept
 comparison: not equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator!= (const_reference lhs, const ScalarType rhs) noexcept
 comparison: not equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator!= (const ScalarType lhs, const_reference rhs) noexcept
 comparison: not equal More...
 
bool operator< (const_reference lhs, const_reference rhs) noexcept
 comparison: less than More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator< (const_reference lhs, const ScalarType rhs) noexcept
 comparison: less than More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator< (const ScalarType lhs, const_reference rhs) noexcept
 comparison: less than More...
 
bool operator<= (const_reference lhs, const_reference rhs) noexcept
 comparison: less than or equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator<= (const_reference lhs, const ScalarType rhs) noexcept
 comparison: less than or equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator<= (const ScalarType lhs, const_reference rhs) noexcept
 comparison: less than or equal More...
 
bool operator> (const_reference lhs, const_reference rhs) noexcept
 comparison: greater than More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator> (const_reference lhs, const ScalarType rhs) noexcept
 comparison: greater than More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator> (const ScalarType lhs, const_reference rhs) noexcept
 comparison: greater than More...
 
bool operator>= (const_reference lhs, const_reference rhs) noexcept
 comparison: greater than or equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator>= (const_reference lhs, const ScalarType rhs) noexcept
 comparison: greater than or equal More...
 
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator>= (const ScalarType lhs, const_reference rhs) noexcept
 comparison: greater than or equal More...
 

serialization

llvm::raw_ostreamoperator<< (llvm::raw_ostream &o, const json &j)
 serialize to stream More...
 

deserialization

wpi::raw_istreamoperator>> (wpi::raw_istream &i, json &j)
 deserialize from stream More...
 
static json parse (llvm::StringRef s, const parser_callback_t cb=nullptr)
 deserialize from string literal More...
 
static json parse (wpi::raw_istream &i, const parser_callback_t cb=nullptr)
 deserialize from stream More...
 

binary serialization/deserialization support

static void to_cbor (llvm::raw_ostream &os, const json &j)
 create a CBOR serialization of a given JSON value More...
 
static llvm::StringRef to_cbor (const json &j, llvm::SmallVectorImpl< char > buf)
 
static std::string to_cbor (const json &j)
 
static void to_msgpack (llvm::raw_ostream &os, const json &j)
 create a MessagePack serialization of a given JSON value More...
 
static llvm::StringRef to_msgpack (const json &j, llvm::SmallVectorImpl< char > buf)
 
static std::string to_msgpack (const json &j)
 
static json from_cbor (wpi::raw_istream &is)
 create a JSON value from a byte vector in CBOR format More...
 
static json from_cbor (llvm::StringRef s)
 
static json from_msgpack (wpi::raw_istream &is)
 create a JSON value from a byte vector in MessagePack format More...
 
static json from_msgpack (llvm::StringRef s)
 

JSON Pointer functions

reference operator[] (const json_pointer &ptr)
 access specified element via JSON Pointer More...
 
const_reference operator[] (const json_pointer &ptr) const
 access specified element via JSON Pointer More...
 
reference at (const json_pointer &ptr)
 access specified element via JSON Pointer More...
 
const_reference at (const json_pointer &ptr) const
 access specified element via JSON Pointer More...
 
json flatten () const
 return flattened JSON value More...
 
json unflatten () const
 unflatten a previously flattened JSON value More...
 

Detailed Description

a class to store JSON values

The class satisfies the following concept requirements:

Invariant
The member variables m_value and m_type have the following relationship:
  • If m_type == value_t::object, then m_value.object != nullptr.
  • If m_type == value_t::array, then m_value.array != nullptr.
  • If m_type == value_t::string, then m_value.string != nullptr. The invariants are checked by member function assert_invariant().
See also
RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format
Since
version 1.0.0

Member Typedef Documentation

using wpi::json::array_t = std::vector<json>

a type for an array

RFC 7159 describes JSON arrays as follows:

An array is an ordered sequence of zero or more values.

To store objects in C++, a type is defined by the template parameters explained below.

Default type

The default value for array_t is:

std::vector<
json // value_type
>

Limits

RFC 7159 specifies:

An implementation may set limits on the maximum depth of nesting.

In this class, the array's limit of nesting is not constraint explicitly. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON array.

Storage

Arrays are stored as pointers in a json type. That is, for any access to array values, a pointer of type array_t* must be dereferenced.

See also
object_ttype for an object value
Since
version 1.0.0
using wpi::json::boolean_t = bool

a type for a boolean

RFC 7159 implicitly describes a boolean as a type which differentiates the two literals true and false.

Default type

The default value for boolean_t is:

bool

Storage

Boolean values are stored directly inside a basic_json type.

Since
version 1.0.0

general exception of the json class

Extension of std::exception objects with a member id for exception ids.

Note
To have nothrow-copy-constructible exceptions, we internally use std::runtime_error which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor.
Since
version 3.0.0

exception indicating errors with iterators

Exceptions have ids 2xx.

name / id example massage description
json.exception.invalid_iterator.201 iterators are not compatible The iterators passed to constructor json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
json.exception.invalid_iterator.202 iterator does not fit current value In an erase or insert function, the passed iterator pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
json.exception.invalid_iterator.203 iterators do not fit current value Either iterator passed to function erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
json.exception.invalid_iterator.204 iterators out of range When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (begin(), end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
json.exception.invalid_iterator.205 iterator out of range When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
json.exception.invalid_iterator.206 cannot construct with iterators from null The iterators passed to constructor json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
json.exception.invalid_iterator.207 cannot use key() for non-object iterators The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
json.exception.invalid_iterator.208 cannot use operator[] for object iterators The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
json.exception.invalid_iterator.209 cannot use offsets with object iterators The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
json.exception.invalid_iterator.210 iterators do not fit The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first, last) is invalid.
json.exception.invalid_iterator.211 passed iterators may not belong to container The iterator range passed to the insert function must not be a subrange of the container to insert to.
json.exception.invalid_iterator.212 cannot compare iterators of different containers When two iterators are compared, they must belong to the same container.
json.exception.invalid_iterator.213 cannot compare order of object iterators The order of object iterators cannot be compated, because JSON objects are unordered.
json.exception.invalid_iterator.214 cannot get value Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin().
Since
version 3.0.0
using wpi::json::number_float_t = double

a type for a number (floating-point)

RFC 7159 describes numbers as follows:

The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.

Default type

The default value for number_float_t is:

double

Default behavior

  • The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal 01.2 will be serialized to 1.2. During deserialization, leading zeros yield an error.
  • Not-a-number (NaN) values will be serialized to null.

Limits

RFC 7159 states:

This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision.

This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than -1.79769313486232e+308 and values greater than 1.79769313486232e+308 will be stored as NaN internally and be serialized to null.

Storage

Floating-point number values are stored directly inside a basic_json type.

See also
number_integer_ttype for number values (integer)
number_unsigned_ttype for number values (unsigned integer)
Since
version 1.0.0
using wpi::json::number_integer_t = int64_t

a type for a number (integer)

RFC 7159 describes numbers as follows:

The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.

Default type

The default value for number_integer_t is:

int64_t

Default behavior

  • The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
  • Not-a-number (NaN) values will be serialized to null.

Limits

RFC 7159 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 9223372036854775807 (INT64_MAX) and the minimal integer number that can be stored is -9223372036854775808 (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_unsigned_t or number_float_t.

RFC 7159 further states:

Note that when such software is used, numbers that are integers and are in the range $[-2^{53}+1, 2^{53}-1]$ are interoperable in the sense that implementations will agree exactly on their numeric values.

As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable.

Storage

Integer number values are stored directly inside a basic_json type.

See also
number_float_ttype for number values (floating-point)
number_unsigned_ttype for number values (unsigned integer)
Since
version 1.0.0
using wpi::json::number_unsigned_t = uint64_t

a type for a number (unsigned)

RFC 7159 describes numbers as follows:

The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted.

This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, number_integer_t, number_unsigned_t and number_float_t are used.

Default type

The default value for number_unsigned_t is:

uint64_t

Default behavior

  • The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal 010 will be serialized to 8. During deserialization, leading zeros yield an error.
  • Not-a-number (NaN) values will be serialized to null.

Limits

RFC 7159 specifies:

An implementation may set limits on the range and precision of numbers.

When the default type is used, the maximal integer number that can be stored is 18446744073709551615 (UINT64_MAX) and the minimal integer number that can be stored is 0. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as number_integer_t or number_float_t.

RFC 7159 further states:

Note that when such software is used, numbers that are integers and are in the range $[-2^{53}+1, 2^{53}-1]$ are interoperable in the sense that implementations will agree exactly on their numeric values.

As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable.

Storage

Integer number values are stored directly inside a basic_json type.

See also
number_float_ttype for number values (floating-point)
number_integer_ttype for number values (integer)
Since
version 2.0.0

a type for an object

RFC 7159 describes JSON objects as follows:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

Behavior

The choice of object_t influences the behavior of the JSON class. With the default type, objects have the following behavior:

  • When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
  • When the names within an object are not unique, later stored name/value pairs overwrite previously stored name/value pairs, leaving the used names unique. For instance, {"key": 1} and {"key": 2, "key": 1} will be treated as equal and both stored as {"key": 1}.
  • Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see dump) in this order. For instance, {"b": 1, "a": 2} and {"a": 2, "b": 1} will be stored and serialized as {"a": 2, "b": 1}.
  • When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, {"b": 1, "a": 2} and {"a": 2, "b": 1} will be treated as equal.

Limits

RFC 7159 specifies:

An implementation may set limits on the maximum depth of nesting.

In this class, the object's limit of nesting is not constraint explicitly. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the max_size function of a JSON object.

Storage

Objects are stored as pointers in a json type. That is, for any access to object values, a pointer of type object_t* must be dereferenced.

See also
array_ttype for an array value
Since
version 1.0.0
Note
The order name/value pairs are added to the object is not preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as std::map with std::less is used by default. Please note this behavior conforms to RFC 7159, because any order implements the specified "unordered" nature of JSON objects.

exception indicating other errors

Exceptions have ids 5xx.

name / id example message description
json.exception.other_error.501 unsuccessful: {"op":"test","path":"/baz", "value":"bar"} A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
json.exception.other_error.502 invalid object size for conversion Some conversions to user-defined types impose constraints on the object size (e.g. std::pair)
Since
version 3.0.0

exception indicating access out of the defined range

Exceptions have ids 4xx.

name / id example message description
json.exception.out_of_range.401 array index 3 is out of range The provided array index i is larger than size-1.
json.exception.out_of_range.402 array index '-' (3) is out of range The special array index - in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
json.exception.out_of_range.403 key 'foo' not found The provided key was not found in the JSON object.
json.exception.out_of_range.404 unresolved reference token 'foo' A reference token in a JSON Pointer could not be resolved.
json.exception.out_of_range.405 JSON pointer has no parent The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
json.exception.out_of_range.406 number overflow parsing '10E1000' A parsed number could not be stored as without changing it to NaN or INF.
Since
version 3.0.0

exception indicating a parse error

This excpetion is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text as well as when using JSON Patch.

Member byte holds the byte index of the last read character in the input file.

Note
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).

Exceptions have ids 1xx.

name / id example massage description
json.exception.parse_error.101 parse error at 2: unexpected end of input; expected string literal This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte indicates the error position.
json.exception.parse_error.102 parse error at 14: missing or wrong low surrogate JSON uses the \uxxxx format to describe Unicode characters. Code points above above 0xFFFF are split into two \uxxxx entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
json.exception.parse_error.103 parse error: code points above 0x10FFFF are invalid Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
json.exception.parse_error.104 parse error: JSON patch must be an array of objects RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.
json.exception.parse_error.105 parse error: operation must have string member 'op' An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
json.exception.parse_error.106 parse error: array index '01' must not begin with '0' An array index in a JSON Pointer (RFC 6901) may be 0 or any number wihtout a leading 0.
json.exception.parse_error.107 parse error: JSON pointer must be empty or begin with '/' - was: 'foo' A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a / character.
json.exception.parse_error.108 parse error: escape character '~' must be followed with '0' or '1' In a JSON Pointer, only ~0 and ~1 are valid escape sequences.
json.exception.parse_error.109 parse error: array index 'one' is not a number A JSON Pointer array index must be a number.
json.exception.parse_error.110 parse error at 1: cannot read 2 bytes from vector When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
json.exception.parse_error.111 parse error: bad input stream Parsing CBOR or MessagePack from an input stream where the badbit or failbit is set.
json.exception.parse_error.112 parse error at 1: error reading CBOR; last byte: 0xf8 Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
json.exception.parse_error.113 parse error at 2: expected a CBOR string; last byte: 0x98 While parsing a map key, a value that is not a string has been read.
Since
version 3.0.0
using wpi::json::parser_callback_t = std::function<bool(int depth, parse_event_t event, json& parsed)>

per-element parser callback type

With a parser callback function, the result of parsing a JSON text can be influenced. When passed to parse(wpi::raw_istream&, const parser_callback_t) or parse(const CharT, const parser_callback_t), it is called on certain events (passed as parse_event_t via parameter event) with a set recursion depth depth and context JSON value parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not.

We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters depth, event, and parsed.

parameter event description parameter depth parameter parsed
parse_event_t::object_start the parser read { and started to process a JSON object depth of the parent of the JSON object a JSON value with type discarded
parse_event_t::key the parser read a key of a value in an object depth of the currently parsed JSON object a JSON string containing the key
parse_event_t::object_end the parser read } and finished processing a JSON object depth of the parent of the JSON object the parsed JSON object
parse_event_t::array_start the parser read [ and started to process a JSON array depth of the parent of the JSON array a JSON value with type discarded
parse_event_t::array_end the parser read ] and finished processing a JSON array depth of the parent of the JSON array the parsed JSON array
parse_event_t::value the parser finished reading a JSON value depth of the value the parsed JSON value
callback_events.png
Example when certain parse events are triggered

Discarding a value (i.e., returning false) has different effects depending on the context in which function was called:

  • Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read.
  • In case a value outside a structured type is skipped, it is replaced with null. This case happens if the top-level element is skipped.
Parameters
[in]depththe depth of the recursion during parsing
[in]eventan event of type parse_event_t indicating the context in the callback function has been called
[in,out]parsedthe current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events
Returns
Whether the JSON value which called the function during parsing should be kept (true) or not (false). In the latter case, it is either skipped completely or replaced by an empty discarded object.
See also
parse(wpi::raw_istream&, parser_callback_t) or parse(const CharT, const parser_callback_t) for examples
Since
version 1.0.0
using wpi::json::string_t = std::string

a type for a string

RFC 7159 describes JSON strings as follows:

A string is a sequence of zero or more Unicode characters.

To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization.

Default type

The default value for string_t is:

std::string

Encoding

Strings are stored in UTF-8 encoding. Therefore, functions like std::string::size() or std::string::length() return the number of bytes in the string rather than the number of characters or glyphs.

String comparison

RFC 7159 states:

Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that "a\\\\b" and "a\\u005Cb" are not equal.

This implementation is interoperable as it does compare strings code unit by code unit.

Storage

String values are stored as pointers in a basic_json type. That is, for any access to string values, a pointer of type string_t* must be dereferenced.

Since
version 1.0.0

exception indicating executing a member function with a wrong type

Exceptions have ids 3xx.

name / id example message description
json.exception.type_error.301 cannot create object from initializer list To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
json.exception.type_error.302 type must be object, but is array During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
json.exception.type_error.303 incompatible ReferenceType for get_ref, actual type is object To retrieve a reference to a value stored in a json object with get_ref, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType must be array_t&.
json.exception.type_error.304 cannot use at() with string The at() member functions can only be executed for certain JSON types.
json.exception.type_error.305 cannot use operator[] with string The operator[] member functions can only be executed for certain JSON types.
json.exception.type_error.306 cannot use value() with string The value() member functions can only be executed for certain JSON types.
json.exception.type_error.307 cannot use erase() with string The erase() member functions can only be executed for certain JSON types.
json.exception.type_error.308 cannot use push_back() with string The push_back() and operator+= member functions can only be executed for certain JSON types.
json.exception.type_error.309 cannot use insert() with The insert() member functions can only be executed for certain JSON types.
json.exception.type_error.310 cannot use swap() with number The swap() member functions can only be executed for certain JSON types.
json.exception.type_error.311 cannot use emplace_back() with string The emplace_back() member function can only be executed for certain JSON types.
json.exception.type_error.313 invalid value to unflatten The unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
json.exception.type_error.314 only objects can be unflattened The unflatten function only works for an object whose keys are JSON Pointers.
json.exception.type_error.315 values in object must be primitive The unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
Since
version 3.0.0

Member Enumeration Documentation

enum wpi::json::parse_event_t : uint8_t
strong

JSON callback events.

This enumeration lists the parser events that can trigger calling a callback function of type parser_callback_t during parsing.

callback_events.png
Example when certain parse events are triggered
Since
version 1.0.0
Enumerator
object_start 

the parser read { and started to process a JSON object

object_end 

the parser read } and finished processing a JSON object

array_start 

the parser read [ and started to process a JSON array

array_end 

the parser read ] and finished processing a JSON array

key 

the parser read a key of a value in an object

value 

the parser finished reading a JSON value

Constructor & Destructor Documentation

wpi::json::json ( const value_t  value_type)
inline

create an empty value with a given type

Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:

Value type initial value
null null
boolean false
string ""
number 0
object {}
array []
Parameters
[in]value_typethe type of the value to create

Constant.

{The following code shows the constructor for different value_t values,json__value_t}

Since
version 1.0.0
wpi::json::json ( std::nullptr_t  = nullptr)
inlinenoexcept

create a null object

Create a null JSON value. It either takes a null pointer as parameter (explicitly creating null) or no parameter (implicitly creating null). The passed null pointer itself is not read – it is only used to choose the right constructor.

Constant.

No-throw guarantee: this constructor never throws exceptions.

{The following code shows the constructor with and without a null pointer parameter.,json__nullptr_t}

Since
version 1.0.0
template<typename CompatibleType , typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t<!std::is_base_of< wpi::raw_istream, U >::value &&!std::is_same< U, json >::value &&!detail::is_json_nested_type< json, U >::value, int > = 0>
wpi::json::json ( CompatibleType &&  val)
inline

create a JSON value

This is a "catch all" constructor for all compatible JSON types; that is, types for which a to_json() method exsits. The constructor forwards the parameter val to that method (to json_serializer<U>::to_json method with U = uncvref_t<CompatibleType>, to be exact).

Template type CompatibleType includes, but is not limited to, the following types:

  • arrays: array_t and all kinds of compatible containers such as std::vector, std::deque, std::list, std::forward_list, std::array, std::set, std::unordered_set, std::multiset, and unordered_multiset with a value_type from which a json value can be constructed.
  • objects: object_t and all kinds of compatible associative containers such as std::map, std::unordered_map, std::multimap, and std::unordered_multimap with a key_type compatible to std::string and a value_type from which a json value can be constructed.
  • strings: std::string, string literals, and all compatible string containers can be used.
  • numbers: std::int64_t, std::uint64_t, double, and all convertible number types such as int, size_t, int64_t, float or double can be used.
  • boolean: bool can be used.

See the examples below.

Template Parameters
CompatibleTypea type such that:
  • CompatibleType is not derived from wpi::raw_istream,
  • CompatibleType is not json (to avoid hijacking copy/move constructors),
  • CompatibleType is not a json nested type (e.g., json_pointer, iterator, etc ...)
  • json_serializer<U> has a to_json(json&, CompatibleType&&) method
U= uncvref_t<CompatibleType>
Parameters
[in]valthe value to be forwarded

Usually linear in the size of the passed val, also depending on the implementation of the called to_json() method.

Exceptions
whatjson_serializer<U>::to_json() throws

{The following code shows the constructor with several compatible types.,json__CompatibleType}

Since
version 2.1.0
json::json ( std::initializer_list< json init,
bool  type_deduction = true,
value_t  manual_type = value_t::array 
)

create a container (array or object) from an initializer list

Creates a JSON value of type array or object from the passed initializer list init. In case type_deduction is true (default), the type of the JSON value to be created is deducted from the initializer list init according to the following rules:

  1. If the list is empty, an empty JSON object value {} is created.
  2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.
  3. In all other cases, an array is created.

The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:

  1. The empty initializer list is written as {} which is exactly an empty JSON object.
  2. C++ has now way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.
  3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe.

With the rules described above, the following JSON values cannot be expressed by an initializer list:

Note
When used without parentheses around an empty initializer list, json() is called instead of this function, yielding the JSON null value.
Parameters
[in]initinitializer list with JSON values
[in]type_deductioninternal parameter; when set to true, the type of the JSON value is deducted from the initializer list init; when set to false, the type provided via manual_type is forced. This mode is used by the functions array(std::initializer_list<json>) and object(std::initializer_list<json>).
[in]manual_typeinternal parameter; when type_deduction is set to false, the created JSON value will use the provided type (only value_t::array and value_t::object are valid); when type_deduction is set to true, this parameter has no effect
Exceptions
type_error.301if type_deduction is false, manual_type is value_t::object, but init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If type_deduction would have be true, an array would have been created. See object(std::initializer_list<json>) for an example.

Linear in the size of the initializer list init.

{The example below shows how JSON values are created from initializer lists.,json__list_init_t}

See also
array(std::initializer_list<json>) – create a JSON array value from an initializer list
object(std::initializer_list<json>) – create a JSON object value from an initializer list
Since
version 1.0.0
json::json ( size_type  cnt,
const json val 
)

construct an array with count copies of given value

Constructs a JSON array value by creating cnt copies of a passed value. In case cnt is 0, an empty array is created. As postcondition, std::distance(begin(),end()) == cnt holds.

Parameters
[in]cntthe number of JSON copies of val to create
[in]valthe JSON value to copy

Linear in cnt.

{The following code shows examples for the json(size_type\, const json&) constructor.,json__size_type_json}

Since
version 1.0.0
template<class InputIT , typename std::enable_if< std::is_same< InputIT, json::iterator >::value||std::is_same< InputIT, json::const_iterator >::value, int >::type = 0>
wpi::json::json ( InputIT  first,
InputIT  last 
)
inline

construct a JSON container given an iterator range

Constructs the JSON value with the contents of the range [first, last). The semantics depends on the different types a JSON value can have:

  • In case of primitive types (number, boolean, or string), first must be begin() and last must be end(). In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown.
  • In case of structured types (array, object), the constructor behaves as similar versions for std::vector.
  • In case of a null type, invalid_iterator.206 is thrown.
Template Parameters
InputITan input iterator type (iterator or const_iterator)
Parameters
[in]firstbegin of the range to copy from (included)
[in]lastend of the range to copy from (excluded)
Precondition
Iterators first and last must be initialized. This precondition is enforced with an assertion.
Range [first, last) is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below.
Exceptions
invalid_iterator.201if iterators first and last are not compatible (i.e., do not belong to the same JSON value). In this case, the range [first, last) is undefined.
invalid_iterator.204if iterators first and last belong to a primitive type (number, boolean, or string), but first does not point to the first element any more. In this case, the range [first, last) is undefined. See example code below.
invalid_iterator.206if iterators first and last belong to a null value. In this case, the range [first, last) is undefined.

Linear in distance between first and last.

{The example below shows several ways to create JSON values by specifying a subrange with iterators.,json__InputIt_InputIt}

Since
version 1.0.0
json::json ( const json other)

copy constructor

Creates a copy of a given JSON value.

Parameters
[in]otherthe JSON value to copy

Linear in the size of other.

This function helps json satisfying the Container requirements:

  • The complexity is linear.
  • As postcondition, it holds: other == json(other).

{The following code shows an example for the copy constructor.,json__json}

Since
version 1.0.0
wpi::json::json ( json &&  other)
inlinenoexcept

move constructor

Move constructor. Constructs a JSON value with the contents of the given value other using move semantics. It "steals" the resources from other and leaves it as JSON null value.

Parameters
[in,out]othervalue to move to this object
Postcondition
other is a JSON null value

Constant.

{The code below shows the move constructor explicitly called via std::move.,json__moveconstructor}

Since
version 1.0.0
json::~json ( )

destructor

Destroys the JSON value and frees all allocated memory.

Linear.

This function helps json satisfying the Container requirements:

  • The complexity is linear.
  • All stored elements are destroyed and all memory is freed.
Since
version 1.0.0

Member Function Documentation

static json wpi::json::array ( std::initializer_list< json init = std::initializer_list<json>())
inlinestatic

explicitly create an array from an initializer list

Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.

Note
This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (json(std::initializer_list<json>, bool, value_t)). These cases are:
  1. creating an array whose elements are all pairs whose first element is a string – in this case, the initializer list constructor would create an object, taking the first elements as keys
  2. creating an empty array – passing the empty initializer list to the initializer list constructor yields an empty object
Parameters
[in]initinitializer list with JSON values to create an array from (optional)
Returns
JSON array value

Linear in the size of init.

{The following code shows an example for the array function.,array}

See also
json(std::initializer_list<json>, bool, value_t) – create a JSON value from an initializer list
object(std::initializer_list<json>) – create a JSON object value from an initializer list
Since
version 1.0.0
json::reference json::at ( size_type  idx)

access specified array element with bounds checking

Returns a reference to the element at specified location idx, with bounds checking.

Parameters
[in]idxindex of the element to access
Returns
reference to the element at index idx
Exceptions
type_error.304if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
out_of_range.401if the index idx is out of range of the array; that is, idx >= size(). See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Constant.

Since
version 1.0.0

{The example below shows how array elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.,at__size_type}

json::const_reference json::at ( size_type  idx) const

access specified array element with bounds checking

Returns a const reference to the element at specified location idx, with bounds checking.

Parameters
[in]idxindex of the element to access
Returns
const reference to the element at index idx
Exceptions
type_error.304if the JSON value is not an array; in this case, calling at with an index makes no sense. See example below.
out_of_range.401if the index idx is out of range of the array; that is, idx >= size(). See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Constant.

Since
version 1.0.0

{The example below shows how array elements can be read using at(). It also demonstrates the different exceptions that can be thrown., at__size_type_const}

json::reference json::at ( llvm::StringRef  key)

access specified object element with bounds checking

Returns a reference to the element at with specified key key, with bounds checking.

Parameters
[in]keykey of the element to access
Returns
reference to the element at key key
Exceptions
type_error.304if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
out_of_range.403if the key key is is not stored in the object; that is, find(key) == end(). See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Logarithmic in the size of the container.

See also
operator[](llvm::StringRef) for unchecked access by reference
value() for access by value with a default value
Since
version 1.0.0

{The example below shows how object elements can be read and written using at(). It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type}

json::const_reference json::at ( llvm::StringRef  key) const

access specified object element with bounds checking

Returns a const reference to the element at with specified key key, with bounds checking.

Parameters
[in]keykey of the element to access
Returns
const reference to the element at key key
Exceptions
type_error.304if the JSON value is not an object; in this case, calling at with a key makes no sense. See example below.
out_of_range.403if the key key is is not stored in the object; that is, find(key) == end(). See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Logarithmic in the size of the container.

See also
operator[](llvm::StringRef) for unchecked access by reference
value() for access by value with a default value
Since
version 1.0.0

{The example below shows how object elements can be read using at(). It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const}

reference wpi::json::at ( const json_pointer ptr)
inline

access specified element via JSON Pointer

Returns a reference to the element at with specified JSON pointer ptr, with bounds checking.

Parameters
[in]ptrJSON pointer to the desired element
Returns
reference to the element pointed to by ptr
Exceptions
parse_error.106if an array index in the passed JSON pointer ptr begins with '0'. See example below.
parse_error.109if an array index in the passed JSON pointer ptr is not a number. See example below.
out_of_range.401if an array index in the passed JSON pointer ptr is out of range. See example below.
out_of_range.402if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
out_of_range.404if the JSON pointer ptr can not be resolved. See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Constant.

Since
version 2.0.0

{The behavior is shown in the example.,at_json_pointer}

const_reference wpi::json::at ( const json_pointer ptr) const
inline

access specified element via JSON Pointer

Returns a const reference to the element at with specified JSON pointer ptr, with bounds checking.

Parameters
[in]ptrJSON pointer to the desired element
Returns
reference to the element pointed to by ptr
Exceptions
parse_error.106if an array index in the passed JSON pointer ptr begins with '0'. See example below.
parse_error.109if an array index in the passed JSON pointer ptr is not a number. See example below.
out_of_range.401if an array index in the passed JSON pointer ptr is out of range. See example below.
out_of_range.402if the array index '-' is used in the passed JSON pointer ptr. As at provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below.
out_of_range.404if the JSON pointer ptr can not be resolved. See example below.

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

Constant.

Since
version 2.0.0

{The behavior is shown in the example.,at_json_pointer_const}

json::reference json::back ( )

access the last element

Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to

auto tmp = c.end();
--tmp;
return *tmp;
Returns
In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned.

Constant.

Precondition
The JSON value must not be null (would throw std::out_of_range) or an empty array or object (undefined behavior, guarded by assertions).
Postcondition
The JSON value remains unchanged.
Exceptions
invalid_iterator.214when called on a null value. See example below.

{The following code shows an example for back().,back}

See also
front() – access the first element
Since
version 1.0.0
json::const_reference json::back ( ) const

access the last element

Returns a reference to the last element in the container. For a JSON container c, the expression c.back() is equivalent to

auto tmp = c.end();
--tmp;
return *tmp;
Returns
In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned.

Constant.

Precondition
The JSON value must not be null (would throw std::out_of_range) or an empty array or object (undefined behavior, guarded by assertions).
Postcondition
The JSON value remains unchanged.
Exceptions
invalid_iterator.214when called on a null value. See example below.

{The following code shows an example for back().,back}

See also
front() – access the first element
Since
version 1.0.0
iterator wpi::json::begin ( )
inlinenoexcept

returns an iterator to the first element

Returns an iterator to the first element.

range-begin-end.svg
Illustration from cppreference.com
Returns
iterator to the first element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.

{The following code shows an example for begin().,begin}

See also
cbegin() – returns a const iterator to the beginning
end() – returns an iterator to the end
cend() – returns a const iterator to the end
Since
version 1.0.0
const_iterator wpi::json::begin ( ) const
inlinenoexcept

returns a const iterator to the first element

Returns a const iterator to the first element.

range-begin-end.svg
Illustration from cppreference.com
Returns
const iterator to the first element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of const_cast<const json&>(*this).begin().

{The following code shows an example for cbegin().,cbegin}

See also
begin() – returns an iterator to the beginning
end() – returns an iterator to the end
cend() – returns a const iterator to the end
Since
version 1.0.0
const_iterator wpi::json::cbegin ( ) const
inlinenoexcept

returns a const iterator to the first element

Returns a const iterator to the first element.

range-begin-end.svg
Illustration from cppreference.com
Returns
const iterator to the first element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of const_cast<const json&>(*this).begin().

{The following code shows an example for cbegin().,cbegin}

See also
begin() – returns an iterator to the beginning
end() – returns an iterator to the end
cend() – returns a const iterator to the end
Since
version 1.0.0
const_iterator wpi::json::cend ( ) const
inlinenoexcept

returns a const iterator to one past the last element

Returns a const iterator to one past the last element.

range-begin-end.svg
Illustration from cppreference.com
Returns
const iterator one past the last element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of const_cast<const json&>(*this).end().

{The following code shows an example for cend().,cend}

See also
end() – returns an iterator to the end
begin() – returns an iterator to the beginning
cbegin() – returns a const iterator to the beginning
Since
version 1.0.0
void json::clear ( )
noexcept

clears the contents

Clears the content of a JSON value and resets it to the default value as if json(value_t) would have been called:

Value type initial value
null null
boolean false
string ""
number 0
object {}
array []

Linear in the size of the JSON value.

{The example below shows the effect of clear() to different JSON types.,clear}

Since
version 1.0.0
size_type wpi::json::count ( llvm::StringRef  key) const
inline

returns the number of occurrences of a key in a JSON object

Returns the number of elements with key key. The return value will always be 0 (key was not found) or 1 (key was found).

Note
This method always returns 0 when executed on a JSON type that is not an object.
Parameters
[in]keykey value of the element to count
Returns
Number of elements with key key. If the JSON value is not an object, the return value will be 0.

Logarithmic in the size of the JSON object.

{The example shows how count() is used.,count}

Since
version 1.0.0
std::string json::dump ( const int  indent = -1) const

serialization

Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent parameter.

Parameters
[in]indentIf indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation.
Returns
string containing the serialization of the JSON value

Linear.

{The following example shows the effect of different indent parameters to the result of the serialization.,dump}

See also
https://docs.python.org/2/library/json.html#json.dump
Since
version 1.0.0; indentaction character added in version 3.0.0
void json::dump ( llvm::raw_ostream os,
int  indent = -1 
) const

serialization

Serialization function for JSON values. The function tries to mimic Python's json.dumps() function, and currently supports its indent parameter.

Parameters
[in,out]osOutput stream
[in]indentIf indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. -1 (the default) selects the most compact representation.

Linear.

{The following example shows the effect of different indent parameters to the result of the serialization.,dump}

See also
https://docs.python.org/2/library/json.html#json.dump
Since
version 1.0.0; indentaction character added in version 3.0.0
template<class... Args>
std::pair<iterator, bool> wpi::json::emplace ( llvm::StringRef  key,
Args &&...  args 
)
inline

add an object to an object if key does not exist

Inserts a new element into a JSON object constructed in-place with the given args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from args.

Parameters
[in]argsarguments to forward to a constructor of json
Template Parameters
Argscompatible types to create a json object
Returns
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place.
Exceptions
type_error.311when called on a type other than JSON object or null; example: "cannot use emplace() with number"

Logarithmic in the size of the container, O(log(size())).

{The example shows how emplace() can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace}

Since
version 2.0.8
template<class... Args>
void wpi::json::emplace_back ( Args &&...  args)
inline

add an object to an array

Creates a JSON value from the passed parameters args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from args.

Parameters
[in]argsarguments to forward to a constructor of json
Template Parameters
Argscompatible types to create a json object
Exceptions
type_error.311when called on a type other than JSON array or null; example: "cannot use emplace_back() with number"

Amortized constant.

{The example shows how push_back() can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.,emplace_back}

Since
version 2.0.8
bool json::empty ( ) const
noexcept

checks whether the container is empty

Checks if a JSON value has no elements.

Returns
The return value depends on the different types and is defined as follows:
Value type return value
null true
boolean false
string false
number false
object result of function object_t::empty()
array result of function array_t::empty()
Note
This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string.

Constant, as long as array_t and object_t satisfy the Container concept; that is, their empty() functions have constant complexity.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of begin() == end().

{The following code uses empty() to check if a JSON object contains any elements.,empty}

See also
size() – returns the number of elements
Since
version 1.0.0
iterator wpi::json::end ( )
inlinenoexcept

returns an iterator to one past the last element

Returns an iterator to one past the last element.

range-begin-end.svg
Illustration from cppreference.com
Returns
iterator one past the last element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.

{The following code shows an example for end().,end}

See also
cend() – returns a const iterator to the end
begin() – returns an iterator to the beginning
cbegin() – returns a const iterator to the beginning
Since
version 1.0.0
const_iterator wpi::json::end ( ) const
inlinenoexcept

returns a const iterator to one past the last element

Returns a const iterator to one past the last element.

range-begin-end.svg
Illustration from cppreference.com
Returns
const iterator one past the last element

Constant.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of const_cast<const json&>(*this).end().

{The following code shows an example for cend().,cend}

See also
end() – returns an iterator to the end
begin() – returns an iterator to the beginning
cbegin() – returns a const iterator to the beginning
Since
version 1.0.0
template<class IteratorType , typename std::enable_if< std::is_same< IteratorType, json::iterator >::value||std::is_same< IteratorType, json::const_iterator >::value, int >::type = 0>
void wpi::json::erase ( IteratorType  pos)
inline

remove element given an iterator

Removes the element specified by iterator pos. The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

If called on a primitive type other than null, the resulting JSON value will be null.

Parameters
[in]positerator to the element to remove
Template Parameters
IteratorTypean iterator or const_iterator
Postcondition
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
Exceptions
type_error.307if called on a null value; example: "cannot use erase() with null"
invalid_iterator.202if called on an iterator which does not belong to the current JSON value; example: "iterator does not fit current value"
invalid_iterator.205if called on a primitive type with invalid iterator (i.e., any iterator which is not begin()); example: "iterator out of range"

The complexity depends on the type:

  • objects: amortized constant
  • arrays: linear in distance between pos and the end of the container
  • strings: linear in the length of the string
  • other types: constant

{The example shows the result of erase() for different JSON types.,erase__IteratorType}

See also
erase(IteratorType, IteratorType) – removes the elements in the given range
erase(llvm::StringRef) – removes the element from an object at the given key
erase(const size_type) – removes the element from an array at the given index
Since
version 1.0.0
template<class IteratorType , typename std::enable_if< std::is_same< IteratorType, json::iterator >::value||std::is_same< IteratorType, json::const_iterator >::value, int >::type = 0>
void wpi::json::erase ( IteratorType  first,
IteratorType  last 
)
inline

remove elements given an iterator range

Removes the element specified by the range [first; last). The iterator first does not need to be dereferenceable if first == last: erasing an empty range is a no-op.

If called on a primitive type other than null, the resulting JSON value will be null.

Parameters
[in]firstiterator to the beginning of the range to remove
[in]lastiterator past the end of the range to remove
Returns
Iterator following the last removed element. If the iterator second refers to the last element, the end() iterator is returned.
Template Parameters
IteratorTypean iterator or const_iterator
Postcondition
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
Exceptions
type_error.307if called on a null value; example: "cannot use erase() with null"
invalid_iterator.203if called on iterators which does not belong to the current JSON value; example: "iterators do not fit current value"
invalid_iterator.204if called on a primitive type with invalid iterators (i.e., if first != begin() and last != end()); example: "iterators out of range"

The complexity depends on the type:

  • objects: log(size()) + std::distance(first, last)
  • arrays: linear in the distance between first and last, plus linear in the distance between last and end of the container
  • strings: linear in the length of the string
  • other types: constant

{The example shows the result of erase() for different JSON types.,erase__IteratorType_IteratorType}

See also
erase(IteratorType) – removes the element at a given position
erase(llvm::StringRef) – removes the element from an object at the given key
erase(const size_type) – removes the element from an array at the given index
Since
version 1.0.0
json::size_type json::erase ( llvm::StringRef  key)

remove element from a JSON object given a key

Removes elements from a JSON object with the key value key.

Parameters
[in]keyvalue of the elements to remove
Returns
Number of elements removed. The return value will always be 0 (key was not found) or 1 (key was found).
Postcondition
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
Exceptions
type_error.307when called on a type other than JSON object; example: "cannot use erase() with null"

log(size()) + count(key)

{The example shows the effect of erase().,erase__key_type}

See also
erase(IteratorType) – removes the element at a given position
erase(IteratorType, IteratorType) – removes the elements in the given range
erase(const size_type) – removes the element from an array at the given index
Since
version 1.0.0
void json::erase ( const size_type  idx)

remove element from a JSON array given an index

Removes element from a JSON array at the index idx.

Parameters
[in]idxindex of the element to remove
Exceptions
type_error.307when called on a type other than JSON object; example: "cannot use erase() with null"
out_of_range.401when idx >= size(); example: "array index 17 is out of range"

Linear in distance between idx and the end of the container.

{The example shows the effect of erase().,erase__size_type}

See also
erase(IteratorType) – removes the element at a given position
erase(IteratorType, IteratorType) – removes the elements in the given range
erase(llvm::StringRef) – removes the element from an object at the given key
Since
version 1.0.0
json::iterator json::find ( llvm::StringRef  key)

find an element in a JSON object

Finds an element in a JSON object with key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.

Note
This method always returns end() when executed on a JSON type that is not an object.
Parameters
[in]keykey value of the element to search for
Returns
Iterator to an element with key equivalent to key. If no such element is found or the JSON value is not an object, past-the-end (see end()) iterator is returned.

Logarithmic in the size of the JSON object.

{The example shows how find() is used.,find__key_type}

Since
version 1.0.0
json::const_iterator json::find ( llvm::StringRef  key) const

find an element in a JSON object

find an element in a JSON object Finds an element in a JSON object with key equivalent to key. If the element is not found or the JSON value is not an object, end() is returned.

Note
This method always returns end() when executed on a JSON type that is not an object.
Parameters
[in]keykey value of the element to search for
Returns
Iterator to an element with key equivalent to key. If no such element is found or the JSON value is not an object, past-the-end (see end()) iterator is returned.

Logarithmic in the size of the JSON object.

{The example shows how find() is used.,find__key_type}

Since
version 1.0.0
json wpi::json::flatten ( ) const
inline

return flattened JSON value

The function creates a JSON object whose keys are JSON pointers (see RFC 6901) and whose values are all primitive. The original JSON value can be restored using the unflatten() function.

Returns
an object that maps JSON pointers to primitive values
Note
Empty objects and arrays are flattened to null and will not be reconstructed correctly by the unflatten() function.

Linear in the size the JSON value.

{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten}

See also
unflatten() for the reverse function
Since
version 2.0.0
json json::from_cbor ( wpi::raw_istream is)
static

create a JSON value from a byte vector in CBOR format

Deserializes a given byte vector v to a JSON value using the CBOR (Concise Binary Object Representation) serialization format.

The library maps CBOR types to JSON value types as follows:

CBOR type JSON value type first byte
Integer number_unsigned 0x00..0x17
Unsigned integer number_unsigned 0x18
Unsigned integer number_unsigned 0x19
Unsigned integer number_unsigned 0x1a
Unsigned integer number_unsigned 0x1b
Negative integer number_integer 0x20..0x37
Negative integer number_integer 0x38
Negative integer number_integer 0x39
Negative integer number_integer 0x3a
Negative integer number_integer 0x3b
Negative integer number_integer 0x40..0x57
UTF-8 string string 0x60..0x77
UTF-8 string string 0x78
UTF-8 string string 0x79
UTF-8 string string 0x7a
UTF-8 string string 0x7b
UTF-8 string string 0x7f
array array 0x80..0x97
array array 0x98
array array 0x99
array array 0x9a
array array 0x9b
array array 0x9f
map object 0xa0..0xb7
map object 0xb8
map object 0xb9
map object 0xba
map object 0xbb
map object 0xbf
False false 0xf4
True  true 0xf5
Nill null 0xf6
Half-Precision Float number_float 0xf9
Single-Precision Float number_float 0xfa
Double-Precision Float number_float 0xfb
Warning
The mapping is incomplete in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112):
  • byte strings (0x40..0x5f)
  • date/time (0xc0..0xc1)
  • bignum (0xc2..0xc3)
  • decimal fraction (0xc4)
  • bigfloat (0xc5)
  • tagged items (0xc6..0xd4, 0xd8..0xdb)
  • expected conversions (0xd5..0xd7)
  • simple values (0xe0..0xf3, 0xf8)
  • undefined (0xf7)
CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113).
Note
Any CBOR output created to_cbor can be successfully parsed by from_cbor.
Parameters
[in]isan input stream in CBOR format
Returns
deserialized JSON value
Exceptions
parse_error.110if the given vector ends prematurely
parse_error.112if unsupported features from CBOR were used in the given vector v or if the input is not valid CBOR
parse_error.113if a string was expected as map key, but not found

Linear in the size of the byte vector v.

{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor}

See also
http://cbor.io
to_cbor(const json&) for the analogous serialization
from_msgpack(const std::vector<uint8_t>&, const size_t) for the related MessagePack format
Since
version 2.0.9, parameter start_index since 2.1.1
json json::from_msgpack ( wpi::raw_istream is)
static

create a JSON value from a byte vector in MessagePack format

Deserializes a given byte vector v to a JSON value using the MessagePack serialization format.

The library maps MessagePack types to JSON value types as follows:

MessagePack type JSON value type first byte
positive fixint number_unsigned 0x00..0x7f
fixmap object 0x80..0x8f
fixarray array 0x90..0x9f
fixstr string 0xa0..0xbf
nil null 0xc0
false false 0xc2
true true 0xc3
float 32 number_float 0xca
float 64 number_float 0xcb
uint 8 number_unsigned 0xcc
uint 16 number_unsigned 0xcd
uint 32 number_unsigned 0xce
uint 64 number_unsigned 0xcf
int 8 number_integer 0xd0
int 16 number_integer 0xd1
int 32 number_integer 0xd2
int 64 number_integer 0xd3
str 8 string 0xd9
str 16 string 0xda
str 32 string 0xdb
array 16 array 0xdc
array 32 array 0xdd
map 16 object 0xde
map 32 object 0xdf
negative fixint number_integer 0xe0-0xff
Warning
The mapping is incomplete in the sense that not all MessagePack types can be converted to a JSON value. The following MessagePack types are not supported and will yield parse errors:
  • bin 8 - bin 32 (0xc4..0xc6)
  • ext 8 - ext 32 (0xc7..0xc9)
  • fixext 1 - fixext 16 (0xd4..0xd8)
Note
Any MessagePack output created to_msgpack can be successfully parsed by from_msgpack.
Parameters
[in]isan input stream in MessagePack format
Returns
deserialized JSON value
Exceptions
parse_error.110if the given vector ends prematurely
parse_error.112if unsupported features from MessagePack were used in the given vector v or if the input is not valid MessagePack
parse_error.113if a string was expected as map key, but not found

Linear in the size of the byte vector v.

{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack}

See also
http://msgpack.org
to_msgpack(const json&) for the analogous serialization
from_cbor(const std::vector<uint8_t>&, const size_t) for the related CBOR format
Since
version 2.0.9, parameter start_index since 2.1.1
reference wpi::json::front ( )
inline

access the first element

Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().

Returns
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned.

Constant.

Precondition
The JSON value must not be null (would throw std::out_of_range) or an empty array or object (undefined behavior, guarded by assertions).
Postcondition
The JSON value remains unchanged.
Exceptions
invalid_iterator.214when called on null value

{The following code shows an example for front().,front}

See also
back() – access the last element
Since
version 1.0.0
const_reference wpi::json::front ( ) const
inline

access the first element

Returns a reference to the first element in the container. For a JSON container c, the expression c.front() is equivalent to *c.begin().

Returns
In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned.

Constant.

Precondition
The JSON value must not be null (would throw std::out_of_range) or an empty array or object (undefined behavior, guarded by assertions).
Postcondition
The JSON value remains unchanged.
Exceptions
invalid_iterator.214when called on null value

{The following code shows an example for front().,front}

See also
back() – access the last element
Since
version 1.0.0
template<typename BasicJsonType , detail::enable_if_t< std::is_same< typename std::remove_const< BasicJsonType >::type, json >::value, int > = 0>
json wpi::json::get ( ) const
inline

get special-case overload

This overloads avoids a lot of template boilerplate, it can be seen as the identity method

Template Parameters
BasicJsonType== json
Returns
a copy of *this

Constant.

Since
version 2.1.0
template<typename ValueTypeCV , typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t< !std::is_same< json, ValueType >::value, int > = 0>
ValueType wpi::json::get ( ) const
inline

get a value (explicit)

Explicit type conversion between the JSON value and a compatible value which is CopyConstructible and DefaultConstructible. The value is converted by calling the json_serializer<ValueType> from_json() method.

The function is equivalent to executing

ValueType ret;
adl_serializer<ValueType, void>::from_json(*this, ret);
return ret;

This overloads is chosen if:

  • ValueType is not json,
  • json_serializer<ValueType> has a from_json() method of the form void from_json(const json&, ValueType&), and
  • json_serializer<ValueType> does not have a from_json() method of the form ValueType from_json(const json&)
Template Parameters
ValueTypeCVthe provided value type
ValueTypethe returned value type
Returns
copy of the JSON value, converted to ValueType
Exceptions
whatjson_serializer<ValueType> from_json() method throws

{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard std::vector<short>\, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string\, json>.,get__ValueType_const}

Since
version 2.1.0
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
PointerType wpi::json::get ( )
inlinenoexcept

get a pointer value (explicit)

Explicit pointer access to the internally stored JSON value. No copies are made.

Warning
The pointer becomes invalid if the underlying JSON object changes.
Template Parameters
PointerTypepointer type; must be a pointer to array_t, object_t, std::string, bool, std::int64_t, std::uint64_t, or double.
Returns
pointer to the internally stored JSON value if the requested pointer type PointerType fits to the JSON value; nullptr otherwise

Constant.

{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.,get__PointerType}

See also
get_ptr() for explicit pointer-member access
Since
version 1.0.0
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
const PointerType wpi::json::get ( ) const
inlinenoexcept

get a pointer value (explicit)

get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made.

Warning
The pointer becomes invalid if the underlying JSON object changes.
Template Parameters
PointerTypepointer type; must be a pointer to array_t, object_t, std::string, bool, std::int64_t, std::uint64_t, or double.
Returns
pointer to the internally stored JSON value if the requested pointer type PointerType fits to the JSON value; nullptr otherwise

Constant.

{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.,get__PointerType}

See also
get_ptr() for explicit pointer-member access
Since
version 1.0.0
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value, int >::type = 0>
PointerType wpi::json::get_ptr ( )
inlinenoexcept

get a pointer value (implicit)

Implicit pointer access to the internally stored JSON value. No copies are made.

Warning
Writing data to the pointee of the result yields an undefined state.
Template Parameters
PointerTypepointer type; must be a pointer to array_t, object_t, std::string, bool, std::int64_t, std::uint64_t, or double. Enforced by a static assertion.
Returns
pointer to the internally stored JSON value if the requested pointer type PointerType fits to the JSON value; nullptr otherwise

Constant.

{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.,get_ptr}

Since
version 1.0.0
template<typename PointerType , typename std::enable_if< std::is_pointer< PointerType >::value &&std::is_const< typename std::remove_pointer< PointerType >::type >::value, int >::type = 0>
const PointerType wpi::json::get_ptr ( ) const
inlinenoexcept

get a pointer value (implicit)

get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made.

Warning
Writing data to the pointee of the result yields an undefined state.
Template Parameters
PointerTypepointer type; must be a pointer to array_t, object_t, std::string, bool, std::int64_t, std::uint64_t, or double. Enforced by a static assertion.
Returns
pointer to the internally stored JSON value if the requested pointer type PointerType fits to the JSON value; nullptr otherwise

Constant.

{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a nullptr is returned if the value and the requested pointer type does not match.,get_ptr}

Since
version 1.0.0
template<typename ReferenceType , typename std::enable_if< std::is_reference< ReferenceType >::value, int >::type = 0>
ReferenceType wpi::json::get_ref ( )
inline

get a reference value (implicit)

Implicit reference access to the internally stored JSON value. No copies are made.

Warning
Writing data to the referee of the result yields an undefined state.
Template Parameters
ReferenceTypereference type; must be a reference to array_t, object_t, std::string, bool, std::int64_t, or double. Enforced by static assertion.
Returns
reference to the internally stored JSON value if the requested reference type ReferenceType fits to the JSON value; throws type_error.303 otherwise
Exceptions
type_error.303in case passed type ReferenceType is incompatible with the stored JSON value; see example below

Constant.

{The example shows several calls to get_ref().,get_ref}

Since
version 1.1.0
template<typename ReferenceType , typename std::enable_if< std::is_reference< ReferenceType >::value &&std::is_const< typename std::remove_reference< ReferenceType >::type >::value, int >::type = 0>
ReferenceType wpi::json::get_ref ( ) const
inline

get a reference value (implicit)

get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made.

Warning
Writing data to the referee of the result yields an undefined state.
Template Parameters
ReferenceTypereference type; must be a reference to array_t, object_t, std::string, bool, std::int64_t, or double. Enforced by static assertion.
Returns
reference to the internally stored JSON value if the requested reference type ReferenceType fits to the JSON value; throws type_error.303 otherwise
Exceptions
type_error.303in case passed type ReferenceType is incompatible with the stored JSON value; see example below

Constant.

{The example shows several calls to get_ref().,get_ref}

Since
version 1.1.0
json::iterator json::insert ( const_iterator  pos,
const json val 
)

inserts element

Inserts element val before iterator pos.

Parameters
[in]positerator before which the content will be inserted; may be the end() iterator
[in]valelement to insert
Returns
iterator pointing to the inserted val.
Exceptions
type_error.309if called on JSON values other than arrays; example: "cannot use insert() with string"
invalid_iterator.202if pos is not an iterator of *this; example: "iterator does not fit current value"

Constant plus linear in the distance between pos and end of the container.

{The example shows how insert() is used.,insert}

Since
version 1.0.0
iterator wpi::json::insert ( const_iterator  pos,
json &&  val 
)
inline

inserts element

inserts element Inserts element val before iterator pos.

Parameters
[in]positerator before which the content will be inserted; may be the end() iterator
[in]valelement to insert
Returns
iterator pointing to the inserted val.
Exceptions
type_error.309if called on JSON values other than arrays; example: "cannot use insert() with string"
invalid_iterator.202if pos is not an iterator of *this; example: "iterator does not fit current value"

Constant plus linear in the distance between pos and end of the container.

{The example shows how insert() is used.,insert}

Since
version 1.0.0
json::iterator json::insert ( const_iterator  pos,
size_type  cnt,
const json val 
)

inserts elements

Inserts cnt copies of val before iterator pos.

Parameters
[in]positerator before which the content will be inserted; may be the end() iterator
[in]cntnumber of copies of val to insert
[in]valelement to insert
Returns
iterator pointing to the first element inserted, or pos if cnt==0
Exceptions
type_error.309if called on JSON values other than arrays; example: "cannot use insert() with string"
invalid_iterator.202if pos is not an iterator of *this; example: "iterator does not fit current value"

Linear in cnt plus linear in the distance between pos and end of the container.

{The example shows how insert() is used.,insert__count}

Since
version 1.0.0
json::iterator json::insert ( const_iterator  pos,
const_iterator  first,
const_iterator  last 
)

inserts elements

Inserts elements from range [first, last) before iterator pos.

Parameters
[in]positerator before which the content will be inserted; may be the end() iterator
[in]firstbegin of the range of elements to insert
[in]lastend of the range of elements to insert
Exceptions
type_error.309if called on JSON values other than arrays; example: "cannot use insert() with string"
invalid_iterator.202if pos is not an iterator of *this; example: "iterator does not fit current value"
invalid_iterator.210if first and last do not belong to the same JSON value; example: "iterators do not fit"
invalid_iterator.211if first or last are iterators into container for which insert is called; example: "passed iterators may not belong to container"
Returns
iterator pointing to the first element inserted, or pos if first==last

Linear in std::distance(first, last) plus linear in the distance between pos and end of the container.

{The example shows how insert() is used.,insert__range}

Since
version 1.0.0
json::iterator json::insert ( const_iterator  pos,
std::initializer_list< json ilist 
)

inserts elements

Inserts elements from initializer list ilist before iterator pos.

Parameters
[in]positerator before which the content will be inserted; may be the end() iterator
[in]ilistinitializer list to insert the values from
Exceptions
type_error.309if called on JSON values other than arrays; example: "cannot use insert() with string"
invalid_iterator.202if pos is not an iterator of *this; example: "iterator does not fit current value"
Returns
iterator pointing to the first element inserted, or pos if ilist is empty

Linear in ilist.size() plus linear in the distance between pos and end of the container.

{The example shows how insert() is used.,insert__ilist}

Since
version 1.0.0
void json::insert ( const_iterator  first,
const_iterator  last 
)

inserts elements

Inserts elements from range [first, last).

Parameters
[in]firstbegin of the range of elements to insert
[in]lastend of the range of elements to insert
Exceptions
type_error.309if called on JSON values other than objects; example: "cannot use insert() with string"
invalid_iterator.202if iterator first or last does does not point to an object; example: "iterators first and last must point to objects"
invalid_iterator.210if first and last do not belong to the same JSON value; example: "iterators do not fit"

Logarithmic: O(N*log(size() + N)), where N is the number of elements to insert.

{The example shows how insert() is used.,insert__range_object}

Since
version 3.0.0
bool wpi::json::is_array ( ) const
inlinenoexcept

return whether value is an array

This function returns true iff the JSON value is an array.

Returns
true if type is array, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_array() for all JSON types.,is_array}

Since
version 1.0.0
bool wpi::json::is_boolean ( ) const
inlinenoexcept

return whether value is a boolean

This function returns true iff the JSON value is a boolean.

Returns
true if type is boolean, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_boolean() for all JSON types.,is_boolean}

Since
version 1.0.0
bool wpi::json::is_discarded ( ) const
inlinenoexcept

return whether value is discarded

This function returns true iff the JSON value was discarded during parsing with a callback function (see parser_callback_t).

Note
This function will always be false for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases.
Returns
true if type is discarded, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_discarded() for all JSON types.,is_discarded}

Since
version 1.0.0
bool wpi::json::is_null ( ) const
inlinenoexcept

return whether value is null

This function returns true iff the JSON value is null.

Returns
true if type is null, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_null() for all JSON types.,is_null}

Since
version 1.0.0
bool wpi::json::is_number ( ) const
inlinenoexcept

return whether value is a number

This function returns true iff the JSON value is a number. This includes both integer and floating-point values.

Returns
true if type is number (regardless whether integer, unsigned integer or floating-type), false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_number() for all JSON types.,is_number}

See also
is_number_integer() – check if value is an integer or unsigned integer number
is_number_unsigned() – check if value is an unsigned integer number
is_number_float() – check if value is a floating-point number
Since
version 1.0.0
bool wpi::json::is_number_float ( ) const
inlinenoexcept

return whether value is a floating-point number

This function returns true iff the JSON value is a floating-point number. This excludes integer and unsigned integer values.

Returns
true if type is a floating-point number, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_number_float() for all JSON types.,is_number_float}

See also
is_number() – check if value is number
is_number_integer() – check if value is an integer number
is_number_unsigned() – check if value is an unsigned integer number
Since
version 1.0.0
bool wpi::json::is_number_integer ( ) const
inlinenoexcept

return whether value is an integer number

This function returns true iff the JSON value is an integer or unsigned integer number. This excludes floating-point values.

Returns
true if type is an integer or unsigned integer number, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_number_integer() for all JSON types.,is_number_integer}

See also
is_number() – check if value is a number
is_number_unsigned() – check if value is an unsigned integer number
is_number_float() – check if value is a floating-point number
Since
version 1.0.0
bool wpi::json::is_number_unsigned ( ) const
inlinenoexcept

return whether value is an unsigned integer number

This function returns true iff the JSON value is an unsigned integer number. This excludes floating-point and (signed) integer values.

Returns
true if type is an unsigned integer number, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_number_unsigned() for all JSON types.,is_number_unsigned}

See also
is_number() – check if value is a number
is_number_integer() – check if value is an integer or unsigned integer number
is_number_float() – check if value is a floating-point number
Since
version 2.0.0
bool wpi::json::is_object ( ) const
inlinenoexcept

return whether value is an object

This function returns true iff the JSON value is an object.

Returns
true if type is object, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_object() for all JSON types.,is_object}

Since
version 1.0.0
bool wpi::json::is_primitive ( ) const
inlinenoexcept

return whether type is primitive

This function returns true iff the JSON type is primitive (string, number, boolean, or null).

Returns
true if type is primitive (string, number, boolean, or null), false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_primitive() for all JSON types.,is_primitive}

See also
is_structured() – returns whether JSON value is structured
is_null() – returns whether JSON value is null
is_string() – returns whether JSON value is a string
is_boolean() – returns whether JSON value is a boolean
is_number() – returns whether JSON value is a number
Since
version 1.0.0
bool wpi::json::is_string ( ) const
inlinenoexcept

return whether value is a string

This function returns true iff the JSON value is a string.

Returns
true if type is string, false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_string() for all JSON types.,is_string}

Since
version 1.0.0
bool wpi::json::is_structured ( ) const
inlinenoexcept

return whether type is structured

This function returns true iff the JSON type is structured (array or object).

Returns
true if type is structured (array or object), false otherwise.

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies is_structured() for all JSON types.,is_structured}

See also
is_primitive() – returns whether value is primitive
is_array() – returns whether value is an array
is_object() – returns whether value is an object
Since
version 1.0.0
static iteration_proxy<iterator> wpi::json::iterator_wrapper ( reference  cont)
inlinestatic

wrapper to access iterator member functions in range-based for

This function allows to access iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.

{The following code shows how the wrapper is used,iterator_wrapper}

Note
The name of this function is not yet final and may change in the future.
static iteration_proxy<const_iterator> wpi::json::iterator_wrapper ( const_reference  cont)
inlinestatic

wrapper to access iterator member functions in range-based for

This function allows to access iterator::key() and iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator.

{The following code shows how the wrapper is used,iterator_wrapper}

Note
The name of this function is not yet final and may change in the future.
json::size_type json::max_size ( ) const
noexcept

returns the maximum possible number of elements

Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the JSON value.

Returns
The return value depends on the different types and is defined as follows:
Value type return value
null 0 (same as size())
boolean 1 (same as size())
string 1 (same as size())
number 1 (same as size())
object result of function object_t::max_size()
array result of function array_t::max_size()
Constant, as long as array_t and object_t satisfy the Container concept; that is, their max_size() functions have constant complexity.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of returning b.size() where b is the largest possible JSON value.

{The following code calls max_size() on the different value types. Note the output is implementation specific.,max_size}

See also
size() – returns the number of elements
Since
version 1.0.0
json json::meta ( )
static

returns version information on the library

This function returns a JSON object with information about the library, including the version number and information on the platform and compiler.

Returns
JSON object holding version information
key description
compiler Information on the used compiler. It is an object with the following keys: c++ (the used C++ standard), family (the compiler family; possible values are clang, icc, gcc, ilecpp, msvc, pgcpp, sunpro, and unknown), and version (the compiler version).
copyright The copyright line for the library as string.
name The name of the library as string.
platform The used platform as string. Possible values are win32, linux, apple, unix, and unknown.
url The URL of the project as string.
version The version of the library. It is an object with the following keys: major, minor, and patch as defined by Semantic Versioning, and string (the version string).
{The following code shows an example output of the meta() function.,meta}

Constant.

Since
2.1.0
static json wpi::json::object ( std::initializer_list< json init = std::initializer_list<json>())
inlinestatic

explicitly create an object from an initializer list

Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object {} is created.

Note
This function is only added for symmetry reasons. In contrast to the related function array(std::initializer_list<json>), there are no cases which can only be expressed by this function. That is, any initializer list init can also be passed to the initializer list constructor json(std::initializer_list<json>, bool, value_t).
Parameters
[in]initinitializer list to create an object from (optional)
Returns
JSON object value
Exceptions
type_error.301if init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to json(std::initializer_list<json>, bool, value_t), an array would have been created from the passed initializer list init. See example below.

Linear in the size of init.

{The following code shows an example for the object function.,object}

See also
json(std::initializer_list<json>, bool, value_t) – create a JSON value from an initializer list
array(std::initializer_list<json>) – create a JSON array value from an initializer list
Since
version 1.0.0
wpi::json::operator value_t ( ) const
inlinenoexcept

return the type of the JSON value (implicit)

Implicitly return the type of the JSON value as a value from the value_t enumeration.

Returns
the type of the JSON value

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies the value_t operator for all JSON types.,operator__value_t}

Since
version 1.0.0
template<typename ValueType , typename std::enable_if< !std::is_pointer< ValueType >::value &&!std::is_same< ValueType, std::string::value_type >::value &&!std::is_same< ValueType, std::initializer_list< std::string::value_type >>::value, int >::type = 0>
wpi::json::operator ValueType ( ) const
inline

get a value (implicit)

Implicit type conversion between the JSON value and a compatible value. The call is realized by calling get() const.

Template Parameters
ValueTypenon-pointer type compatible to the JSON value, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. The character type of std::string as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to std::string.
Returns
copy of the JSON value, converted to type ValueType
Exceptions
type_error.302in case passed type ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below

Linear in the size of the JSON value.

{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard std::vector<short>\, (3) A JSON object can be converted to C++ associative containers such as std::unordered_map<std::string\, json>.,operator__ValueType}

Since
version 1.0.0
reference wpi::json::operator+= ( json &&  val)
inline

add an object to an array

add an object to an array Appends the given element val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending val.

Parameters
[in]valthe value to add to the JSON array
Exceptions
type_error.308when called on a type other than JSON array or null; example: "cannot use push_back() with number"

Amortized constant.

{The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.,push_back}

Since
version 1.0.0
reference wpi::json::operator+= ( const json val)
inline

add an object to an array

add an object to an array Appends the given element val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending val.

Parameters
[in]valthe value to add to the JSON array
Exceptions
type_error.308when called on a type other than JSON array or null; example: "cannot use push_back() with number"

Amortized constant.

{The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.,push_back}

Since
version 1.0.0
reference wpi::json::operator+= ( const std::pair< llvm::StringRef, json > &  val)
inline

add an object to an object

reference wpi::json::operator+= ( std::initializer_list< json init)
inline

add an object to an object

add an object to an object This function allows to use push_back with an initializer list. In case

  1. the current value is an object,
  2. the initializer list init contains only two elements, and
  3. the first element of init is a string,

init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(json&&).

Parameters
[in]initan initializer list

Linear in the size of the initializer list init.

Note
This function is required to resolve an ambiguous overload error, because pairs like {"key", "value"} can be both interpreted as object_t::value_type or std::initializer_list<json>, see https://github.com/nlohmann/json/issues/235 for more information.

{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list}

reference& wpi::json::operator= ( json  other)
inlinenoexcept

copy assignment

Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the swap() member function.

Parameters
[in]othervalue to copy from

Linear.

This function helps json satisfying the Container requirements:

  • The complexity is linear.

{The code below shows and example for the copy assignment. It creates a copy of value a which is then swapped with b. Finally\, the copy of a (which is the null value after the swap) is destroyed.,json__copyassignment}

Since
version 1.0.0
json::reference json::operator[] ( size_type  idx)

access specified array element

Returns a reference to the element at specified location idx.

Note
If idx is beyond the range of the array (i.e., idx >= size()), then the array is silently filled up with null values to make idx a valid reference to the last stored element.
Parameters
[in]idxindex of the element to access
Returns
reference to the element at index idx
Exceptions
type_error.305if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense.

Constant if idx is in the range of the array. Otherwise linear in idx - size().

{The example below shows how array elements can be read and written using [] operator. Note the addition of null values.,operatorarray__size_type}

Since
version 1.0.0
json::const_reference json::operator[] ( size_type  idx) const

access specified array element

Returns a const reference to the element at specified location idx.

Parameters
[in]idxindex of the element to access
Returns
const reference to the element at index idx
Exceptions
type_error.305if the JSON value is not an array; in that cases, using the [] operator with an index makes no sense.

Constant.

{The example below shows how array elements can be read using the [] operator.,operatorarray__size_type_const}

Since
version 1.0.0
json::reference json::operator[] ( llvm::StringRef  key)

access specified object element

Returns a reference to the element at with specified key key.

Note
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
Parameters
[in]keykey of the element to access
Returns
reference to the element at key key
Exceptions
type_error.305if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read and written using the [] operator.,operatorarray__key_type}

See also
at(llvm::StringRef) for access by reference with range checking
value() for access by value with a default value
Since
version 1.0.0
json::const_reference json::operator[] ( llvm::StringRef  key) const

read-only access specified object element

Returns a const reference to the element at with specified key key. No bounds checking is performed.

Warning
If the element with key key does not exist, the behavior is undefined.
Parameters
[in]keykey of the element to access
Returns
const reference to the element at key key
Precondition
The element with key key must exist. This precondition is enforced with an assertion.
Exceptions
type_error.305if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read using the [] operator.,operatorarray__key_type_const}

See also
at(llvm::StringRef) for access by reference with range checking
value() for access by value with a default value
Since
version 1.0.0
template<typename T , std::size_t n>
reference wpi::json::operator[] ( T *(&)  key[n])
inline

access specified object element

Returns a reference to the element at with specified key key.

Note
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
Parameters
[in]keykey of the element to access
Returns
reference to the element at key key
Exceptions
type_error.305if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read and written using the [] operator.,operatorarray__key_type}

See also
at(const typename object_t::key_type&) for access by reference with range checking
value() for access by value with a default value
Since
version 1.0.0
template<typename T , std::size_t n>
const_reference wpi::json::operator[] ( T *(&)  key[n]) const
inline

read-only access specified object element

Returns a const reference to the element at with specified key key. No bounds checking is performed.

Warning
If the element with key key does not exist, the behavior is undefined.
Note
This function is required for compatibility reasons with Clang.
Parameters
[in]keykey of the element to access
Returns
const reference to the element at key key
Exceptions
type_error.305if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read using the [] operator.,operatorarray__key_type_const}

See also
at(const typename object_t::key_type&) for access by reference with range checking
value() for access by value with a default value
Since
version 1.0.0
template<typename T >
reference wpi::json::operator[] ( T *  key)
inline

access specified object element

Returns a reference to the element at with specified key key.

Note
If key is not found in the object, then it is silently added to the object and filled with a null value to make key a valid reference. In case the value was null before, it is converted to an object.
Parameters
[in]keykey of the element to access
Returns
reference to the element at key key
Exceptions
type_error.305if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read and written using the [] operator.,operatorarray__key_type}

See also
at(const typename object_t::key_type&) for access by reference with range checking
value() for access by value with a default value
Since
version 1.1.0
template<typename T >
const_reference wpi::json::operator[] ( T *  key) const
inline

read-only access specified object element

Returns a const reference to the element at with specified key key. No bounds checking is performed.

Warning
If the element with key key does not exist, the behavior is undefined.
Parameters
[in]keykey of the element to access
Returns
const reference to the element at key key
Precondition
The element with key key must exist. This precondition is enforced with an assertion.
Exceptions
type_error.305if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be read using the [] operator.,operatorarray__key_type_const}

See also
at(const typename object_t::key_type&) for access by reference with range checking
value() for access by value with a default value
Since
version 1.1.0
reference wpi::json::operator[] ( const json_pointer ptr)
inline

access specified element via JSON Pointer

Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to operator[]( llvm::StringRef), null values are created in arrays and objects if necessary.

In particular:

  • If the JSON pointer points to an object key that does not exist, it is created an filled with a null value before a reference to it is returned.
  • If the JSON pointer points to an array index that does not exist, it is created an filled with a null value before a reference to it is returned. All indices between the current maximum and the given index are also filled with null.
  • The special value - is treated as a synonym for the index past the end.
Parameters
[in]ptra JSON pointer
Returns
reference to the element pointed to by ptr

Constant.

Exceptions
parse_error.106if an array index begins with '0'
parse_error.109if an array index was not a number
out_of_range.404if the JSON pointer can not be resolved

{The behavior is shown in the example.,operatorjson_pointer}

Since
version 2.0.0
const_reference wpi::json::operator[] ( const json_pointer ptr) const
inline

access specified element via JSON Pointer

Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no null values are created. In particular, the the special value - yields an exception.

Parameters
[in]ptrJSON pointer to the desired element
Returns
const reference to the element pointed to by ptr

Constant.

Exceptions
parse_error.106if an array index begins with '0'
parse_error.109if an array index was not a number
out_of_range.402if the array index '-' is used
out_of_range.404if the JSON pointer can not be resolved

{The behavior is shown in the example.,operatorjson_pointer_const}

Since
version 2.0.0
json json::parse ( llvm::StringRef  s,
const parser_callback_t  cb = nullptr 
)
static

deserialize from string literal

Template Parameters
CharTcharacter/literal type with size of 1 byte
Parameters
[in]sstring literal to read a serialized JSON value from
[in]cba parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional)
Returns
result of the deserialization
Exceptions
parse_error.101in case of an unexpected token
parse_error.102if to_unicode fails or surrogate error
parse_error.103if to_unicode fails

Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb has a super-linear complexity.

Note
A UTF-8 byte order mark is silently ignored.
String containers like std::string can be parsed with parse(const ContiguousContainer&, const parser_callback_t)

{The example below demonstrates the parse() function with and without callback function.,parse__string__parser_callback_t}

See also
parse(wpi::raw_istream&, const parser_callback_t) for a version that reads from an input stream
Since
version 1.0.0 (originally for std::string)
json json::parse ( wpi::raw_istream i,
const parser_callback_t  cb = nullptr 
)
static

deserialize from stream

Parameters
[in,out]istream to read a serialized JSON value from
[in]cba parser callback function of type parser_callback_t which is used to control the deserialization by filtering unwanted values (optional)
Returns
result of the deserialization
Exceptions
parse_error.101in case of an unexpected token
parse_error.102if to_unicode fails or surrogate error
parse_error.103if to_unicode fails
parse_error.111if input stream is in a bad state

Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function cb has a super-linear complexity.

Note
A UTF-8 byte order mark is silently ignored.

{The example below demonstrates the parse() function with and without callback function.,parse__raw_istream__parser_callback_t}

See also
parse(const CharT, const parser_callback_t) for a version that reads from a string
Since
version 1.0.0
void json::push_back ( json &&  val)

add an object to an array

Appends the given element val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending val.

Parameters
[in]valthe value to add to the JSON array
Exceptions
type_error.308when called on a type other than JSON array or null; example: "cannot use push_back() with number"

Amortized constant.

{The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.,push_back}

Since
version 1.0.0
void json::push_back ( const json val)

add an object to an array

add an object to an array Appends the given element val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending val.

Parameters
[in]valthe value to add to the JSON array
Exceptions
type_error.308when called on a type other than JSON array or null; example: "cannot use push_back() with number"

Amortized constant.

{The example shows how push_back() and += can be used to add elements to a JSON array. Note how the null value was silently converted to a JSON array.,push_back}

Since
version 1.0.0
void json::push_back ( const std::pair< llvm::StringRef, json > &  val)

add an object to an object

Inserts the given element val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting val.

Parameters
[in]valthe value to add to the JSON object
Exceptions
type_error.308when called on a type other than JSON object or null; example: "cannot use push_back() with number"

Logarithmic in the size of the container, O(log(size())).

{The example shows how push_back() and += can be used to add elements to a JSON object. Note how the null value was silently converted to a JSON object.,push_back__object_t__value}

Since
version 1.0.0
void json::push_back ( std::initializer_list< json init)

add an object to an object

This function allows to use push_back with an initializer list. In case

  1. the current value is an object,
  2. the initializer list init contains only two elements, and
  3. the first element of init is a string,

init is converted into an object element and added using push_back(const typename object_t::value_type&). Otherwise, init is converted to a JSON value and added using push_back(json&&).

Parameters
[in]initan initializer list

Linear in the size of the initializer list init.

Note
This function is required to resolve an ambiguous overload error, because pairs like {"key", "value"} can be both interpreted as object_t::value_type or std::initializer_list<json>, see https://github.com/nlohmann/json/issues/235 for more information.

{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list}

json::size_type json::size ( ) const
noexcept

returns the number of elements

Returns the number of elements in a JSON value.

Returns
The return value depends on the different types and is defined as follows:
Value type return value
null 0
boolean 1
string 1
number 1
object result of function object_t::size()
array result of function array_t::size()
Note
This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string.

Constant, as long as array_t and object_t satisfy the Container concept; that is, their size() functions have constant complexity.

This function helps json satisfying the Container requirements:

  • The complexity is constant.
  • Has the semantics of std::distance(begin(), end()).

{The following code calls size() on the different value types.,size}

See also
empty() – checks whether the container is empty
max_size() – returns the maximal number of elements
Since
version 1.0.0
void wpi::json::swap ( reference  other)
inlinenoexcept

exchanges the values

Exchanges the contents of the JSON value with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.

Parameters
[in,out]otherJSON value to exchange the contents with

Constant.

{The example below shows how JSON values can be swapped with swap().,swap__reference}

Since
version 1.0.0
void wpi::json::swap ( array_t other)
inline

exchanges the values

Exchanges the contents of a JSON array with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.

Parameters
[in,out]otherarray to exchange the contents with
Exceptions
type_error.310when JSON value is not an array; example: "cannot use swap() with string"

Constant.

{The example below shows how arrays can be swapped with swap().,swap__array_t}

Since
version 1.0.0
void wpi::json::swap ( object_t other)
inline

exchanges the values

Exchanges the contents of a JSON object with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.

Parameters
[in,out]otherobject to exchange the contents with
Exceptions
type_error.310when JSON value is not an object; example: "cannot use swap() with string"

Constant.

{The example below shows how objects can be swapped with swap().,swap__object_t}

Since
version 1.0.0
void wpi::json::swap ( std::string &  other)
inline

exchanges the values

Exchanges the contents of a JSON string with those of other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.

Parameters
[in,out]otherstring to exchange the contents with
Exceptions
type_error.310when JSON value is not a string; example: "cannot use swap() with boolean"

Constant.

{The example below shows how strings can be swapped with swap().,swap__std::string}

Since
version 1.0.0
void json::to_cbor ( llvm::raw_ostream os,
const json j 
)
static

create a CBOR serialization of a given JSON value

Serializes a given JSON value j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.

The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049):

JSON value type value/range CBOR type first byte
null null Null 0xf6
boolean true True 0xf5
boolean false False 0xf4
number_integer -9223372036854775808..-2147483649 Negative integer (8 bytes follow) 0x3b
number_integer -2147483648..-32769 Negative integer (4 bytes follow) 0x3a
number_integer -32768..-129 Negative integer (2 bytes follow) 0x39
number_integer -128..-25 Negative integer (1 byte follow) 0x38
number_integer -24..-1 Negative integer 0x20..0x37
number_integer 0..23 Integer 0x00..0x17
number_integer 24..255 Unsigned integer (1 byte follow) 0x18
number_integer 256..65535 Unsigned integer (2 bytes follow) 0x19
number_integer 65536..4294967295 Unsigned integer (4 bytes follow) 0x1a
number_integer 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1b
number_unsigned 0..23 Integer 0x00..0x17
number_unsigned 24..255 Unsigned integer (1 byte follow) 0x18
number_unsigned 256..65535 Unsigned integer (2 bytes follow) 0x19
number_unsigned 65536..4294967295 Unsigned integer (4 bytes follow) 0x1a
number_unsigned 4294967296..18446744073709551615 Unsigned integer (8 bytes follow) 0x1b
number_float any value Double-Precision Float 0xfb
string length: 0..23 UTF-8 string 0x60..0x77
string length: 23..255 UTF-8 string (1 byte follow) 0x78
string length: 256..65535 UTF-8 string (2 bytes follow) 0x79
string length: 65536..4294967295 UTF-8 string (4 bytes follow) 0x7a
string length: 4294967296..18446744073709551615 UTF-8 string (8 bytes follow) 0x7b
array size: 0..23 array 0x80..0x97
array size: 23..255 array (1 byte follow) 0x98
array size: 256..65535 array (2 bytes follow) 0x99
array size: 65536..4294967295 array (4 bytes follow) 0x9a
array size: 4294967296..18446744073709551615 array (8 bytes follow) 0x9b
object size: 0..23 map 0xa0..0xb7
object size: 23..255 map (1 byte follow) 0xb8
object size: 256..65535 map (2 bytes follow) 0xb9
object size: 65536..4294967295 map (4 bytes follow) 0xba
object size: 4294967296..18446744073709551615 map (8 bytes follow) 0xbb
Note
The mapping is complete in the sense that any JSON value type can be converted to a CBOR value.
The following CBOR types are not used in the conversion:
  • byte strings (0x40..0x5f)
  • UTF-8 strings terminated by "break" (0x7f)
  • arrays terminated by "break" (0x9f)
  • maps terminated by "break" (0xbf)
  • date/time (0xc0..0xc1)
  • bignum (0xc2..0xc3)
  • decimal fraction (0xc4)
  • bigfloat (0xc5)
  • tagged items (0xc6..0xd4, 0xd8..0xdb)
  • expected conversions (0xd5..0xd7)
  • simple values (0xe0..0xf3, 0xf8)
  • undefined (0xf7)
  • half and single-precision floats (0xf9-0xfa)
  • break (0xff)
Parameters
[in,out]osoutput stream
[in]jJSON value to serialize

Linear in the size of the JSON value j.

{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor}

See also
http://cbor.io
from_cbor(const std::vector<uint8_t>&, const size_t) for the analogous deserialization
to_msgpack(const json& for the related MessagePack format
Since
version 2.0.9
void json::to_msgpack ( llvm::raw_ostream os,
const json j 
)
static

create a MessagePack serialization of a given JSON value

Serializes a given JSON value j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.

The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification:

JSON value type value/range MessagePack type first byte
null null nil 0xc0
boolean true true 0xc3
boolean false false 0xc2
number_integer -9223372036854775808..-2147483649 int64 0xd3
number_integer -2147483648..-32769 int32 0xd2
number_integer -32768..-129 int16  0xd1
number_integer -128..-33 int8 0xd0
number_integer -32..-1 negative fixint 0xe0..0xff
number_integer 0..127 positive fixint 0x00..0x7f
number_integer 128..255 uint 8  0xcc
number_integer 256..65535 uint 16 0xcd
number_integer 65536..4294967295 uint 32 0xce
number_integer 4294967296..18446744073709551615 uint 64 0xcf
number_unsigned 0..127 positive fixint 0x00..0x7f
number_unsigned 128..255 uint 8  0xcc
number_unsigned 256..65535 uint 16 0xcd
number_unsigned 65536..4294967295 uint 32 0xce
number_unsigned 4294967296..18446744073709551615 uint 64 0xcf
number_float any value float 64 0xcb
string length: 0..31 fixstr 0xa0..0xbf
string length: 32..255 str 8 0xd9
string length: 256..65535 str 16 0xda
string length: 65536..4294967295 str 32 0xdb
array size: 0..15 fixarray 0x90..0x9f
array size: 16..65535 array 16 0xdc
array size: 65536..4294967295 array 32 0xdd
object size: 0..15 fix map 0x80..0x8f
object size: 16..65535 map 16 0xde
object size: 65536..4294967295 map 32 0xdf
Note
The mapping is complete in the sense that any JSON value type can be converted to a MessagePack value.
The following values can not be converted to a MessagePack value:
  • strings with more than 4294967295 bytes
  • arrays with more than 4294967295 elements
  • objects with more than 4294967295 elements
The following MessagePack types are not used in the conversion:
  • bin 8 - bin 32 (0xc4..0xc6)
  • ext 8 - ext 32 (0xc7..0xc9)
  • float 32 (0xca)
  • fixext 1 - fixext 16 (0xd4..0xd8)
Any MessagePack output created to_msgpack can be successfully parsed by from_msgpack.
Parameters
[in,out]osoutput stream
[in]jJSON value to serialize

Linear in the size of the JSON value j.

{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack}

See also
http://msgpack.org
from_msgpack(const std::vector<uint8_t>&, const size_t) for the analogous deserialization
to_cbor(const json& for the related CBOR format
Since
version 2.0.9
value_t wpi::json::type ( ) const
inlinenoexcept

return the type of the JSON value (explicit)

Return the type of the JSON value as a value from the value_t enumeration.

Returns
the type of the JSON value

Constant.

No-throw guarantee: this member function never throws exceptions.

{The following code exemplifies type() for all JSON types.,type}

Since
version 1.0.0
std::string json::type_name ( ) const

return the type as string

Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type.

Returns
basically a string representation of a the m_type member

Constant.

{The following code exemplifies type_name() for all JSON types.,type_name}

Since
version 1.0.0, public since 2.1.0
json wpi::json::unflatten ( ) const
inline

unflatten a previously flattened JSON value

The function restores the arbitrary nesting of a JSON value that has been flattened before using the flatten() function. The JSON value must meet certain constraints:

  1. The value must be an object.
  2. The keys must be JSON pointers (see RFC 6901)
  3. The mapped values must be primitive JSON types.
Returns
the original JSON from a flattened version
Note
Empty objects and arrays are flattened by flatten() to null values and can not unflattened to their original type. Apart from this example, for a JSON value j, the following is always true: j == j.flatten().unflatten().

Linear in the size the JSON value.

Exceptions
type_error.314if value is not an object
type_error.315if object values are not primitve

{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten}

See also
flatten() for the reverse function
Since
version 2.0.0
template<class ValueType , typename std::enable_if< std::is_convertible< json, ValueType >::value, int >::type = 0>
ValueType wpi::json::value ( llvm::StringRef  key,
ValueType  default_value 
) const
inline

access specified object element with default value

Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

The function is basically equivalent to executing

try {
return at(key);
} catch(out_of_range) {
return default_value;
}
Note
Unlike at(llvm::StringRef), this function does not throw if the given key key was not found.
Unlike operator[](llvm::StringRef key), this function does not implicitly add an element to the position defined by key. This function is furthermore also applicable to const objects.
Parameters
[in]keykey of the element to access
[in]default_valuethe value to return if key is not found
Template Parameters
ValueTypetype compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key and the default value default_value must be compatible.
Returns
copy of the element at key key or default_value if key is not found
Exceptions
type_error.306if the JSON value is not an objec; in that cases, using value() with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be queried with a default value.,json__value}

See also
at(llvm::StringRef) for access by reference with range checking
operator[](llvm::StringRef) for unchecked access by reference
Since
version 1.0.0
std::string wpi::json::value ( llvm::StringRef  key,
const char *  default_value 
) const
inline

overload for a default value of type const char*

access specified object element with default value Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

The function is basically equivalent to executing

try {
return at(key);
} catch(out_of_range) {
return default_value;
}
Note
Unlike at(llvm::StringRef), this function does not throw if the given key key was not found.
Unlike operator[](llvm::StringRef key), this function does not implicitly add an element to the position defined by key. This function is furthermore also applicable to const objects.
Parameters
[in]keykey of the element to access
[in]default_valuethe value to return if key is not found
Template Parameters
ValueTypetype compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key and the default value default_value must be compatible.
Returns
copy of the element at key key or default_value if key is not found
Exceptions
type_error.306if the JSON value is not an objec; in that cases, using value() with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be queried with a default value.,json__value}

See also
at(llvm::StringRef) for access by reference with range checking
operator[](llvm::StringRef) for unchecked access by reference
Since
version 1.0.0
template<class ValueType , typename std::enable_if< std::is_convertible< json, ValueType >::value, int >::type = 0>
ValueType wpi::json::value ( const json_pointer ptr,
ValueType  default_value 
) const
inline

access specified object element via JSON Pointer with default value

Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

The function is basically equivalent to executing

try {
return at(ptr);
} catch(out_of_range) {
return default_value;
}
Note
Unlike at(const json_pointer&), this function does not throw if the given key key was not found.
Parameters
[in]ptra JSON pointer to the element to access
[in]default_valuethe value to return if ptr found no value
Template Parameters
ValueTypetype compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key and the default value default_value must be compatible.
Returns
copy of the element at key key or default_value if key is not found
Exceptions
type_error.306if the JSON value is not an objec; in that cases, using value() with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be queried with a default value.,json__value_ptr}

See also
operator[](const json_pointer&) for unchecked access by reference
Since
version 2.0.2
std::string wpi::json::value ( const json_pointer ptr,
const char *  default_value 
) const
inline

overload for a default value of type const char*

access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key key or a given default value if no element with key key exists.

The function is basically equivalent to executing

try {
return at(ptr);
} catch(out_of_range) {
return default_value;
}
Note
Unlike at(const json_pointer&), this function does not throw if the given key key was not found.
Parameters
[in]ptra JSON pointer to the element to access
[in]default_valuethe value to return if ptr found no value
Template Parameters
ValueTypetype compatible to JSON values, for instance int for JSON integer numbers, bool for JSON booleans, or std::vector types for JSON arrays. Note the type of the expected value at key and the default value default_value must be compatible.
Returns
copy of the element at key key or default_value if key is not found
Exceptions
type_error.306if the JSON value is not an objec; in that cases, using value() with a key makes no sense.

Logarithmic in the size of the container.

{The example below shows how object elements can be queried with a default value.,json__value_ptr}

See also
operator[](const json_pointer&) for unchecked access by reference
Since
version 2.0.2

Friends And Related Function Documentation

bool operator!= ( const_reference  lhs,
const_reference  rhs 
)
friend

comparison: not equal

Compares two JSON values for inequality by calculating not (lhs == rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are not equal

Linear.

{The example demonstrates comparing several JSON types.,operator__notequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator!= ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: not equal

comparison: not equal Compares two JSON values for inequality by calculating not (lhs == rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are not equal

Linear.

{The example demonstrates comparing several JSON types.,operator__notequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator!= ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: not equal

comparison: not equal Compares two JSON values for inequality by calculating not (lhs == rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are not equal

Linear.

{The example demonstrates comparing several JSON types.,operator__notequal}

Since
version 1.0.0
bool operator< ( json::const_reference  lhs,
json::const_reference  rhs 
)
friend

comparison: less than

Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:

  • If lhs and rhs have the same type, the values are compared using the default < operator.
  • Integer and floating-point numbers are automatically converted before comparison
  • In case lhs and rhs have different types, the values are ignored and the order of the types is considered, see operator<(const value_t, const value_t).
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__less}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator< ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: less than

comparison: less than Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:

  • If lhs and rhs have the same type, the values are compared using the default < operator.
  • Integer and floating-point numbers are automatically converted before comparison
  • In case lhs and rhs have different types, the values are ignored and the order of the types is considered, see operator<(const value_t, const value_t).
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__less}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator< ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: less than

comparison: less than Compares whether one JSON value lhs is less than another JSON value rhs according to the following rules:

  • If lhs and rhs have the same type, the values are compared using the default < operator.
  • Integer and floating-point numbers are automatically converted before comparison
  • In case lhs and rhs have different types, the values are ignored and the order of the types is considered, see operator<(const value_t, const value_t).
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__less}

Since
version 1.0.0
llvm::raw_ostream& operator<< ( llvm::raw_ostream o,
const json j 
)
friend

serialize to stream

Serialize the given JSON value j to the output stream o. The JSON value will be serialized using the dump member function.

  • The indentation of the output can be controlled with the member variable width of the output stream o. For instance, using the manipulator std::setw(4) on o sets the indentation level to 4 and the serialization result is the same as calling dump(4).
  • The indentation characrer can be controlled with the member variable fill of the output stream o. For instance, the manipulator `std::setfill('\t')` sets indentation to use a tab character rather than the default space character.
Parameters
[in,out]ostream to serialize to
[in]jJSON value to serialize
Returns
the stream o

Linear.

{The example below shows the serialization with different parameters to width to adjust the indentation level.,operator_serialize}

Since
version 1.0.0; indentaction character added in version 3.0.0
bool operator<= ( const_reference  lhs,
const_reference  rhs 
)
friend

comparison: less than or equal

Compares whether one JSON value lhs is less than or equal to another JSON value by calculating not (rhs < lhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greater}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator<= ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: less than or equal

comparison: less than or equal Compares whether one JSON value lhs is less than or equal to another JSON value by calculating not (rhs < lhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greater}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator<= ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: less than or equal

comparison: less than or equal Compares whether one JSON value lhs is less than or equal to another JSON value by calculating not (rhs < lhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is less than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greater}

Since
version 1.0.0
bool operator== ( json::const_reference  lhs,
json::const_reference  rhs 
)
friend

comparison: equal

Compares two JSON values for equality according to the following rules:

  • Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective operator==.
  • Integer and floating-point numbers are automatically converted before comparison. Floating-point numbers are compared indirectly: two floating-point numbers f1 and f2 are considered equal if neither f1 > f2 nor f2 > f1 holds. Note than two NaN values are always treated as unequal.
  • Two JSON null values are equal.
Note
NaN values never compare equal to themselves or to other NaN values.
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are equal

Linear.

{The example demonstrates comparing several JSON types.,operator__equal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator== ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: equal

comparison: equal Compares two JSON values for equality according to the following rules:

  • Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective operator==.
  • Integer and floating-point numbers are automatically converted before comparison. Floating-point numbers are compared indirectly: two floating-point numbers f1 and f2 are considered equal if neither f1 > f2 nor f2 > f1 holds. Note than two NaN values are always treated as unequal.
  • Two JSON null values are equal.
Note
NaN values never compare equal to themselves or to other NaN values.
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are equal

Linear.

{The example demonstrates comparing several JSON types.,operator__equal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator== ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: equal

comparison: equal Compares two JSON values for equality according to the following rules:

  • Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective operator==.
  • Integer and floating-point numbers are automatically converted before comparison. Floating-point numbers are compared indirectly: two floating-point numbers f1 and f2 are considered equal if neither f1 > f2 nor f2 > f1 holds. Note than two NaN values are always treated as unequal.
  • Two JSON null values are equal.
Note
NaN values never compare equal to themselves or to other NaN values.
Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether the values lhs and rhs are equal

Linear.

{The example demonstrates comparing several JSON types.,operator__equal}

Since
version 1.0.0
bool operator> ( const_reference  lhs,
const_reference  rhs 
)
friend

comparison: greater than

Compares whether one JSON value lhs is greater than another JSON value by calculating not (lhs <= rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__lessequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator> ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: greater than

comparison: greater than Compares whether one JSON value lhs is greater than another JSON value by calculating not (lhs <= rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__lessequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator> ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: greater than

comparison: greater than Compares whether one JSON value lhs is greater than another JSON value by calculating not (lhs <= rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__lessequal}

Since
version 1.0.0
bool operator>= ( const_reference  lhs,
const_reference  rhs 
)
friend

comparison: greater than or equal

Compares whether one JSON value lhs is greater than or equal to another JSON value by calculating not (lhs < rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greaterequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator>= ( const_reference  lhs,
const ScalarType  rhs 
)
friend

comparison: greater than or equal

comparison: greater than or equal Compares whether one JSON value lhs is greater than or equal to another JSON value by calculating not (lhs < rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greaterequal}

Since
version 1.0.0
template<typename ScalarType , typename std::enable_if< std::is_scalar< ScalarType >::value, int >::type = 0>
bool operator>= ( const ScalarType  lhs,
const_reference  rhs 
)
friend

comparison: greater than or equal

comparison: greater than or equal Compares whether one JSON value lhs is greater than or equal to another JSON value by calculating not (lhs < rhs).

Parameters
[in]lhsfirst JSON value to consider
[in]rhssecond JSON value to consider
Returns
whether lhs is greater than or equal to rhs

Linear.

{The example demonstrates comparing several JSON types.,operator__greaterequal}

Since
version 1.0.0
wpi::raw_istream& operator>> ( wpi::raw_istream i,
json j 
)
friend

deserialize from stream

Deserializes an input stream to a JSON value.

Parameters
[in,out]iinput stream to read a serialized JSON value from
[in,out]jJSON value to write the deserialized input to
Exceptions
parse_error.101in case of an unexpected token
parse_error.102if to_unicode fails or surrogate error
parse_error.103if to_unicode fails
parse_error.111if input stream is in a bad state

Linear in the length of the input. The parser is a predictive LL(1) parser.

Note
A UTF-8 byte order mark is silently ignored.

{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize}

See also
parse(wpi::raw_istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing
Since
version 1.0.0

The documentation for this class was generated from the following files: