docs
Loading...
Searching...
No Matches
JSON

#include <Ultralight/JSON.h>

Overview

JSON document or value for structured data.

You use JSON to work with structured data. You can parse a document from text or build one in code. Operations never throw exceptions, so missing keys or syntax errors won't crash your application.

Call JSON::Parse() to parse JSON text and check for syntax errors:

JSON prefs = JSON::Parse(json_text);
if (!prefs)
printf("line %u: %s\n", prefs.error_line(),
prefs.error_message().utf8().data());
static JSON Parse(const String &text)
Parse JSON text.
unsigned error_line() const
Get the 1-based line number of the parse error (0 unless this is a failed Parse() result).
JSON()
Create an empty, invalid JSON value.
String error_message() const
Get the parse error description ("" unless this is a failed Parse() result).
char * data()
Get raw UTF-8 data.
Definition String8.h:53
String8 & utf8()
Get native UTF-8 string.
Definition String.h:109

Reading Values

You can chain operator[] across keys or indices without checking each step. A missing key, an out-of-range index, or the wrong kind of value anywhere in the chain safely resolves to the fallback passed to Or().

Read nested values with fallback defaults:

void ApplyPrefs(const JSON& prefs) {
double ui_scale = prefs["ui"]["scale"].Or(1.0); // 1.0 if missing
String player_name = prefs["profile"]["name"].Or("anonymous");
bool muted = prefs["audio"]["muted"].Or(false);
}
double Or(double fallback) const
Read this value as a number.
Unicode string container with conversions for UTF-8, UTF-16, and UTF-32.
Definition String.h:31

The Or() method reads a value matching the fallback's type without converting between types (reading "3" with a fallback of 0 returns 0). An integer fallback truncates a fractional number toward zero.

Always read values through a const JSON reference. Indexing a non-const document creates missing objects along the path automatically.

Note
Testing a lookup in a conditional checks whether the key exists rather than its boolean value. A key holding false still evaluates to true in a conditional. Pass false to Or() to read a JSON boolean.

Iterating Objects and Arrays

Iterate over an object's members using a range-for loop over AsObject():

void ConnectAll(const JSON& prefs) {
for (auto [server, address] : prefs["servers"].AsObject())
Connect(server, address.Or(""));
}
JSONObject AsObject() const
Get a typed view of this value as an object (for iteration, Has(), and size()).

Call AsArray() to iterate over array elements (see JSONArray). See JSONObject for object iteration.

Building Documents

Start a new document by calling JSON::Object() or JSON::Array(). Indexing a non-const document with operator[] returns an assignable reference (see JSON::Ref). To build an array, assign JSON::Array() before indexing elements, or call Push() through AsArray() to append items.

Populate nested values and serialize the document to text:

JSON save = JSON::Object();
save["player"]["name"] = "ada"; // creates "player" first
save["player"]["level"] = 12;
save["unlocks"] = JSON::Array();
save["unlocks"][0] = "tutorial_done";
JSON unlocks = save["unlocks"];
unlocks.AsArray().Push("first_boss");
String saved_text = save.Stringify(2); // two spaces per level
void Push(const JSON &value)
Append value, sharing its document.
String Stringify(unsigned indent=0) const
Serialize this value to JSON text.
JSONArray AsArray() const
Get a typed view of this value as an array (for iteration, size(), and Push()).
static JSON Object()
Create a new empty object value.
static JSON Array()
Create a new empty array value.

Copying Documents

A copy shares the document, and a JSON assigned into a document shares its value as well. A change made through one copy shows up in every other copy and in any document the value was assigned into.

Copy a document to share it, or call Clone() to make an independent copy:

JSON shared = save; // the same document
JSON copy = save.Clone(); // an independent copy
JSON Clone() const
Deep-copy this value into an independent document.
Warning
Only one thread at a time may access a document. Because copies share the underlying data, accessing copies across threads requires your own synchronization.
See also
JSON::Ref, JSONObject, JSONArray

Classes

struct  Member
 One object member, as visited by JSONObject iteration. More...
class  Ref
 Assignable reference to a value inside a mutable JSON document. More...

Static Public Member Functions

static JSON Parse (const String &text)
 Parse JSON text.
static JSON Object ()
 Create a new empty object value.
static JSON Array ()
 Create a new empty array value.

Public Member Functions

 JSON ()
 Create an empty, invalid JSON value.
 JSON (const JSON &other)
 Create a copy of another JSON.
 JSON (JSON &&other)
 Move constructor.
 ~JSON ()
 Destructor.
JSON & operator= (const JSON &other)
 Assignment operator.
JSON & operator= (JSON &&other)
 Move assignment operator.
bool is_valid () const
 Whether or not this JSON holds a value.
 operator bool () const
 Whether or not this JSON holds a value (the same as is_valid()).
String error_message () const
 Get the parse error description ("" unless this is a failed Parse() result).
unsigned error_line () const
 Get the 1-based line number of the parse error (0 unless this is a failed Parse() result).
bool is_object () const
 Whether or not this value is an object.
bool is_array () const
 Whether or not this value is an array.
bool is_string () const
 Whether or not this value is a string.
bool is_number () const
 Whether or not this value is a number.
bool is_bool () const
 Whether or not this value is a boolean.
bool is_null () const
 Whether or not this value is null.
JSON operator[] (const String &key) const
 Read an object member.
JSON operator[] (size_t index) const
 Read an array element.
Ref operator[] (const String &key)
 Get an assignable reference to an object member.
Ref operator[] (size_t index)
 Get an assignable reference to an array element.
double Or (double fallback) const
 Read this value as a number.
int64_t Or (long long fallback) const
 Read this value as a number, truncated toward zero to an integer.
int64_t Or (int fallback) const
 Same as Or(long long).
int64_t Or (unsigned fallback) const
 Same as Or(long long).
int64_t Or (long fallback) const
 Same as Or(long long).
int64_t Or (unsigned long fallback) const
 Same as Or(long long).
int64_t Or (unsigned long long fallback) const
 Same as Or(long long).
double Or (float fallback) const
 Same as Or(double).
bool Or (bool fallback) const
 Read this value as a boolean.
String Or (const String &fallback) const
 Read this value as a string.
String Or (const char *fallback) const
 Same as Or(const String&).
JSONObject AsObject () const
 Get a typed view of this value as an object (for iteration, Has(), and size()).
JSONArray AsArray () const
 Get a typed view of this value as an array (for iteration, size(), and Push()).
String Stringify (unsigned indent=0) const
 Serialize this value to JSON text.
JSON Clone () const
 Deep-copy this value into an independent document.

Friends

class JSONObject
class JSONArray

Constructor & Destructor Documentation

◆ JSON() [1/3]

JSON ( )

Create an empty, invalid JSON value.

It has no error message.

You can assign another JSON to it later.

◆ JSON() [2/3]

JSON ( const JSON & other)

Create a copy of another JSON.

The copy shares the same document (see the class overview).

Note
Use Clone() for an independent copy.

◆ JSON() [3/3]

JSON ( JSON && other)

Move constructor.

The moved-from handle becomes empty and invalid.

◆ ~JSON()

~JSON ( )

Destructor.

Member Function Documentation

◆ Array()

JSON Array ( )
static

Create a new empty array value.

◆ AsArray()

JSONArray AsArray ( ) const

Get a typed view of this value as an array (for iteration, size(), and Push()).

Returns
Returns the view. A non-array value or an invalid JSON returns an empty view.
Note
A const JSON doesn't protect an array from appends– Push() still works through the view.

◆ AsObject()

JSONObject AsObject ( ) const

Get a typed view of this value as an object (for iteration, Has(), and size()).

Returns
Returns the view. A non-object value or an invalid JSON returns an empty view.

◆ Clone()

JSON Clone ( ) const

Deep-copy this value into an independent document.

Plain copies share the document (see the class overview).

Returns
Returns the copy, or an invalid JSON if this JSON is invalid.

◆ error_line()

unsigned error_line ( ) const

Get the 1-based line number of the parse error (0 unless this is a failed Parse() result).

◆ error_message()

String error_message ( ) const

Get the parse error description ("" unless this is a failed Parse() result).

◆ is_array()

bool is_array ( ) const

Whether or not this value is an array.

◆ is_bool()

bool is_bool ( ) const

Whether or not this value is a boolean.

◆ is_null()

bool is_null ( ) const

Whether or not this value is null.

◆ is_number()

bool is_number ( ) const

Whether or not this value is a number.

◆ is_object()

bool is_object ( ) const

Whether or not this value is an object.

◆ is_string()

bool is_string ( ) const

Whether or not this value is a string.

◆ is_valid()

bool is_valid ( ) const

Whether or not this JSON holds a value.

This returns false for a failed parse, a default-constructed JSON, a moved-from JSON, or a lookup that found nothing.

◆ Object()

JSON Object ( )
static

Create a new empty object value.

◆ operator bool()

operator bool ( ) const
inlineexplicit

Whether or not this JSON holds a value (the same as is_valid()).

Note
This tests whether a value is present, not the JSON boolean value (see the class overview).

◆ operator=() [1/2]

JSON & operator= ( const JSON & other)

Assignment operator.

This JSON now shares other's value.

Note
This doesn't write into the value this JSON referred to before– use json[...] = value instead.

◆ operator=() [2/2]

JSON & operator= ( JSON && other)

Move assignment operator.

◆ operator[]() [1/4]

Ref operator[] ( const String & key)

Get an assignable reference to an object member.

Assigning through the reference writes the member.

Chaining [] creates missing members as objects along the path.

Parameters
keyThe member name.
Returns
Returns a reference to the member (see JSON::Ref).
Note
On a non-object value, writes through the reference do nothing.

◆ operator[]() [2/4]

JSON operator[] ( const String & key) const

Read an object member.

You can index the result again without checking it first (see the class overview).

Parameters
keyThe member name.
Returns
Returns a JSON sharing the member's value. A missing key, a non-object value, or an invalid JSON returns an invalid JSON.

◆ operator[]() [3/4]

Ref operator[] ( size_t index)

Get an assignable reference to an array element.

Writing past the end pads the array with nulls, up to 65536 elements past the end.

Writes further out are ignored.

Parameters
indexThe element index.
Returns
Returns a reference to the element (see JSON::Ref).
Note
On a non-array value, writes through the reference do nothing.

◆ operator[]() [4/4]

JSON operator[] ( size_t index) const

Read an array element.

Parameters
indexThe element index.
Returns
Returns a JSON sharing the element's value. An out-of-range index, a non-array value, or an invalid JSON returns an invalid JSON.

◆ Or() [1/11]

bool Or ( bool fallback) const

Read this value as a boolean.

Parameters
fallbackThe value to return when this value is not a boolean.
Returns
Returns the boolean or fallback.

◆ Or() [2/11]

String Or ( const char * fallback) const

Same as Or(const String&).

◆ Or() [3/11]

String Or ( const String & fallback) const

Read this value as a string.

Parameters
fallbackThe value to return when this value is not a string.
Returns
Returns the string or fallback.

◆ Or() [4/11]

double Or ( double fallback) const

Read this value as a number.

Parameters
fallbackThe value to return when this value is not a number.
Returns
Returns the number or fallback.

◆ Or() [5/11]

double Or ( float fallback) const

Same as Or(double).

◆ Or() [6/11]

int64_t Or ( int fallback) const

Same as Or(long long).

◆ Or() [7/11]

int64_t Or ( long fallback) const

Same as Or(long long).

◆ Or() [8/11]

int64_t Or ( long long fallback) const

Read this value as a number, truncated toward zero to an integer.

Parameters
fallbackThe value to return when this value is not a number.
Returns
Returns the truncated number or fallback. Numbers beyond the 64-bit range clamp to the nearest representable integer. NaN reads as 0.

◆ Or() [9/11]

int64_t Or ( unsigned fallback) const

Same as Or(long long).

◆ Or() [10/11]

int64_t Or ( unsigned long fallback) const

Same as Or(long long).

◆ Or() [11/11]

int64_t Or ( unsigned long long fallback) const

Same as Or(long long).

◆ Parse()

JSON Parse ( const String & text)
static

Parse JSON text.

The top level accepts any JSON value (object, array, string, number, boolean, or null).

Parameters
textThe JSON text to parse (UTF-8).
Returns
Returns the parsed document. On failure, is_valid() returns false, and error_message() and error_line() describe the first syntax error.
Note
Input nested deeper than 1000 levels or larger than 256 MB fails to parse.

◆ Stringify()

String Stringify ( unsigned indent = 0) const

Serialize this value to JSON text.

Parameters
indentThe number of spaces per nesting level. Pass 0 for compact single-line output.
Returns
Returns the JSON text, or "" when this value is invalid.

◆ JSONArray

friend class JSONArray
friend

◆ JSONObject

friend class JSONObject
friend

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