Table of Contents
- Read JSON
- Read JSON from string
- Read JSON from file
- Read JSON with options
- Reader flag
- Write JSON
- Write JSON to string
- Write JSON to file
- Write JSON with options
- Writer flag
- Access JSON Document
- JSON Document
- JSON Value
- JSON Value Content
- JSON Array
- JSON Array Iterator
- JSON Object
- JSON Object Iterator
- JSON Pointer
- Create JSON Document
- Mutable Document API
- Mutable JSON Value Creation
- Mutable JSON Array Creation
- Mutable JSON Array Modification
- Mutable JSON Array Modification (Convenience)
- Mutable JSON Object Creation
- Mutable JSON Object Modification
- Mutable JSON Object Modification (Convenience)
- JSON Merge Pacth
- Number Processing
- Number Reader
- Number Writer
- Text Processing
- Character Encoding
- NUL Character
- Memory Allocator
- Single allocator for multiple JSON
- Stack memory allocator
- Use third-party allocator library
- Mutable and Immutable
- Null Check
- Thread Safe
- Locale Dependent
Read JSON
yyjson provides 3 methods for reading JSON,
each method accepts an input of UTF-8 data or file,
returns a document if succeeds, or returns NULL if fails.
Read JSON from string
The dat
should be a UTF-8 string, null-terminator is not required.
The len
is the byte length of dat
.
The flg
is reader flag, pass 0 if you don't need it, see reader flag for details.
If input is invalid, NULL
is returned.
size_t len,
uint32_t yyjson_read_flag
Definition: yyjson.h:561
yyjson_api_inline yyjson_doc * yyjson_read(const char *dat, size_t len, yyjson_read_flag flg)
Definition: yyjson.h:738
Definition: yyjson.h:3271
Sample code:
const char *str = "[1,2,3,4]";
if (doc) {...}
yyjson_api_inline void yyjson_doc_free(yyjson_doc *doc)
Definition: yyjson.h:3454
Read JSON from file
The path
is JSON file path.
The flg
is reader flag, pass 0 if you don't need it, see reader flag for details.
The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
The err
is a pointer to receive error message, pass NULL if you don't need it.
If input is invalid, NULL
is returned.
yyjson_api yyjson_doc * yyjson_read_file(const char *path, yyjson_read_flag flg, const yyjson_alc *alc, yyjson_read_err *err)
Sample code:
Read JSON with options
The dat
should be a UTF-8 string, you can pass a const string if you don't use YYJSON_READ_INSITU
flag.
The len
is the dat
's length in bytes.
The flg
is reader flag, pass 0 if you don't need it, see reader flag for details.
The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
The err
is a pointer to receive error message, pass NULL if you don't need it.
size_t len,
yyjson_api yyjson_doc * yyjson_read_opts(char *dat, size_t len, yyjson_read_flag flg, const yyjson_alc *alc, yyjson_read_err *err)
Sample code:
const char *dat = your_file.bytes;
size_t len = your_file.size;
yyjson_err err;
if (doc) {...}
else printf("read error: %s code: %u at position: %ld\n", err.msg, err.code, err.pos);
static const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN
Definition: yyjson.h:595
static const yyjson_read_flag YYJSON_READ_ALLOW_COMMENTS
Definition: yyjson.h:591
Reader flag
yyjson provides a set of flags for JSON reader.
You can use a single flag, or combine multiple flags with bitwise |
operator.
● YYJSON_READ_NOFLAG = 0
This is the default flag for JSON reader (RFC-8259 or ECMA-404 compliant):
- Read positive integer as
uint64_t
.
- Read negative integer as
int64_t
.
- Read floating-point number as
double
with correct rounding.
- Read integer which cannot fit in
uint64_t
or int64_t
as double
.
- Report error if real number is infinity.
- Report error if string contains invalid UTF-8 character or BOM.
- Report error on trailing commas, comments,
inf
and nan
literals.
● YYJSON_READ_INSITU
Read the input data in-situ.
This option allows the reader to modify and use input data to store string values, which can increase reading speed slightly. The caller should hold the input data before free the document. The input data must be padded by at least YYJSON_PADDING_SIZE
byte. For example: "[1,2]" should be "[1,2]\0\0\0\0", length should be 5.
Sample code:
size_t dat_len = ...;
char *buf = malloc(dat_len + 4);
read_from_socket(buf, ...);
memset(buf + file_size, 0, 4);
if (doc) {...}
free(buf);
static const yyjson_read_flag YYJSON_READ_INSITU
Definition: yyjson.h:579
● YYJSON_READ_STOP_WHEN_DONE
Stop when done instead of issues an error if there's additional content after a JSON document.
This option may used to parse small pieces of JSON in larger data, such as NDJSON.
Sample code:
size_t file_size = ...;
char *dat = malloc(file_size + 4);
your_read_file(dat, file);
memset(dat + file_size, 0, 4);
char *hdr = dat;
char *end = dat + file_size;
while (true) {
if (!doc) break;
your_doc_process(doc);
}
free(dat);
yyjson_api_inline size_t yyjson_doc_get_read_size(yyjson_doc *doc)
Definition: yyjson.h:3446
static const yyjson_read_flag YYJSON_READ_STOP_WHEN_DONE
Definition: yyjson.h:584
● YYJSON_READ_ALLOW_TRAILING_COMMAS
Allow single trailing comma at the end of an object or array, for example:
{
"a": 1,
"b": 2,
}
[
"a",
"b",
]
● YYJSON_READ_ALLOW_COMMENTS
Allow C-style single line and multiple line comments, for example:
{
"name": "Harry", // single line comment
"id": /* multiple line comment */ 123
}
● YYJSON_READ_ALLOW_INF_AND_NAN
Allow nan/inf number or literal (case-insensitive), such as 1e999, NaN, Inf, -Infinity, for example:
{
"large": 123e999,
"nan1": NaN,
"nan2": nan,
"inf1:" Inf,
"inf2": -Infinity
}
● YYJSON_READ_NUMBER_AS_RAW
Read numbers as raw strings without parsing, allowing you to keep arbitrarily large numbers.
You can use these functions to extract raw strings:
bool yyjson_is_raw(yyjson_val *val);
const char *yyjson_get_raw(yyjson_val *val);
size_t yyjson_get_len(yyjson_val *val)
● YYJSON_READ_ALLOW_INVALID_UNICODE
Allow reading invalid unicode when parsing string values, for example:
"\x80xyz"
"\xF0\x81\x81\x81"
Invalid characters will be allowed to appear in the string values, but invalid escape sequences will still be reported as errors.
This flag does not affect the performance of correctly encoded string.
Be careful when dealing with malformed unicode strings!
Write JSON
yyjson provides 3 methods for writing JSON,
each method accepts an input of JSON document or root value, returns a UTF-8 string or file.
Write JSON to string
The doc/val
is JSON document or root value, if you pass NULL, you will get NULL result.
The flg
is writer flag, pass 0 if you don't need it, see writer flag for details.
The len
is a pointer to receive output length, pass NULL if you don't need it.
This function returns a new JSON string, or NULL if error occurs.
The string is encoded as UTF-8 with a null-terminator.
You should use free() or alc->free() to release it when it's no longer needed.
yyjson_api_inline char * yyjson_val_write(const yyjson_val *val, yyjson_write_flag flg, size_t *len)
Definition: yyjson.h:1114
yyjson_api_inline char * yyjson_mut_val_write(const yyjson_mut_val *val, yyjson_write_flag flg, size_t *len)
Definition: yyjson.h:1192
yyjson_api_inline char * yyjson_mut_write(const yyjson_mut_doc *doc, yyjson_write_flag flg, size_t *len)
Definition: yyjson.h:1033
yyjson_api_inline char * yyjson_write(const yyjson_doc *doc, yyjson_write_flag flg, size_t *len)
Definition: yyjson.h:953
uint32_t yyjson_write_flag
Definition: yyjson.h:809
Definition: yyjson.h:3858
Definition: yyjson.h:3826
Definition: yyjson.h:3266
Sample code 1:
printf("%s\n", json);
free(json);
static const yyjson_write_flag YYJSON_WRITE_PRETTY
Definition: yyjson.h:819
Sample code 2:
printf("%s\n", json);
free(json);
yyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc, yyjson_mut_val *root)
Definition: yyjson.h:3919
yyjson_api_inline bool yyjson_mut_arr_add_int(yyjson_mut_doc *doc, yyjson_mut_val *arr, int64_t num)
Definition: yyjson.h:4801
yyjson_api yyjson_mut_doc * yyjson_mut_doc_new(const yyjson_alc *alc)
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr(yyjson_mut_doc *doc)
Definition: yyjson.h:4339
Write JSON to file
The path
is output JSON file path, If the path is invalid, you will get an error. If the file is not empty, the content will be discarded.
The doc/val
is JSON document or root value, if you pass NULL, you will get an error.
The flg
is writer flag, pass 0 if you don't need it, see writer flag for details.
The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
The err
is a pointer to receive error message, pass NULL if you don't need it.
This function returns true on success, or false if error occurs.
yyjson_api bool yyjson_write_file(const char *path, const yyjson_doc *doc, yyjson_write_flag flg, const yyjson_alc *alc, yyjson_write_err *err)
yyjson_api bool yyjson_val_write_file(const char *path, const yyjson_val *val, yyjson_write_flag flg, const yyjson_alc *alc, yyjson_write_err *err)
yyjson_api bool yyjson_mut_write_file(const char *path, const yyjson_mut_doc *doc, yyjson_write_flag flg, const yyjson_alc *alc, yyjson_write_err *err)
yyjson_api bool yyjson_mut_val_write_file(const char *path, const yyjson_mut_val *val, yyjson_write_flag flg, const yyjson_alc *alc, yyjson_write_err *err)
Sample code:
Write JSON with options
The doc/val
is JSON document or root value, if you pass NULL, you will get NULL result.
The flg
is writer flag, pass 0 if you don't need it, see writer flag for details.
The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
The len
is a pointer to receive output length, pass NULL if you don't need it.
The err
is a pointer to receive error message, pass NULL if you don't need it.
This function returns a new JSON string, or NULL if error occurs.
The string is encoded as UTF-8 with a null-terminator.
You should use free() or alc->free() to release it when it's no longer needed.
size_t *len,
size_t *len,
size_t *len,
size_t *len,
yyjson_api char * yyjson_write_opts(const yyjson_doc *doc, yyjson_write_flag flg, const yyjson_alc *alc, size_t *len, yyjson_write_err *err)
yyjson_api char * yyjson_val_write_opts(const yyjson_val *val, yyjson_write_flag flg, const yyjson_alc *alc, size_t *len, yyjson_write_err *err)
yyjson_api char * yyjson_mut_write_opts(const yyjson_mut_doc *doc, yyjson_write_flag flg, const yyjson_alc *alc, size_t *len, yyjson_write_err *err)
yyjson_api char * yyjson_mut_val_write_opts(const yyjson_mut_val *val, yyjson_write_flag flg, const yyjson_alc *alc, size_t *len, yyjson_write_err *err)
Sample code:
char buf[64 * 1024];
size_t len;
if (json) {
printf("suc: %lu\n%s\n", len, json);
} else {
printf(
"err: %u msg:%s\n", err.
code, err.
msg);
}
void(* free)(void *ctx, void *ptr)
Definition: yyjson.h:480
void * ctx
Definition: yyjson.h:482
const char * msg
Definition: yyjson.h:875
yyjson_api bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, size_t size)
static const yyjson_write_flag YYJSON_WRITE_ESCAPE_UNICODE
Definition: yyjson.h:822
yyjson_write_code code
Definition: yyjson.h:873
Writer flag
yyjson provides a set of flags for JSON writer.
You can use a single flag, or combine multiple flags with bitwise |
operator.
● YYJSON_WRITE_NOFLAG = 0
This is the default flag for JSON writer:
- Write JSON minify.
- Report error on inf or nan number.
- Report error on invalid UTF-8 string.
- Do not escape unicode or slash.
● YYJSON_WRITE_PRETTY
Write JSON pretty with 4 space indent.
● YYJSON_WRITE_ESCAPE_UNICODE
Escape unicode as \uXXXX
, make the output ASCII only, for example:
["Alizée, 😊"]
["Aliz\\u00E9e, \\uD83D\\uDE0A"]
● YYJSON_WRITE_ESCAPE_SLASHES
Escape /
as \/
, for example:
["https://github.com"]
["https:\/\/github.com"]
● YYJSON_WRITE_ALLOW_INF_AND_NAN
Write inf/nan number as Infinity
and NaN
literals.
Note that this output is NOT standard JSON and may be rejected by other JSON libraries, for example:
{"not a number":NaN,"large number":Infinity}
● YYJSON_WRITE_INF_AND_NAN_AS_NULL
Write inf/nan number as null
literal.
This flag will override YYJSON_WRITE_ALLOW_INF_AND_NAN
flag, for example:
{"not a number":null,"large number":null}
● YYJSON_WRITE_ALLOW_INVALID_UNICODE
Allow invalid unicode when encoding string values.
Invalid characters in string value will be copied byte by byte. If YYJSON_WRITE_ESCAPE_UNICODE
flag is also set, invalid character will be escaped as \uFFFD
(replacement character).
This flag does not affect the performance of correctly encoded string.
Access JSON Document
JSON Document API
Returns the root value of this JSON document.
yyjson_api_inline yyjson_val * yyjson_doc_get_root(yyjson_doc *doc)
Definition: yyjson.h:3442
Returns read size of input JSON data.
Returns total value count in this JSON document.
yyjson_api_inline size_t yyjson_doc_get_val_count(yyjson_doc *doc)
Definition: yyjson.h:3450
Release the JSON document and free the memory.
JSON Value API
Returns true if the JSON value is specified type.
Returns false if the input is NULL
or not the specified type.
This set of APIs also have version for mutable values, see mutable and immutable for details.
yyjson_api_inline bool yyjson_is_ctn(yyjson_val *val)
Definition: yyjson.h:3520
yyjson_api_inline bool yyjson_is_bool(yyjson_val *val)
Definition: yyjson.h:3484
yyjson_api_inline bool yyjson_is_real(yyjson_val *val)
Definition: yyjson.h:3500
yyjson_api_inline bool yyjson_is_int(yyjson_val *val)
Definition: yyjson.h:3496
yyjson_api_inline bool yyjson_is_true(yyjson_val *val)
Definition: yyjson.h:3476
yyjson_api_inline bool yyjson_is_str(yyjson_val *val)
Definition: yyjson.h:3508
yyjson_api_inline bool yyjson_is_false(yyjson_val *val)
Definition: yyjson.h:3480
yyjson_api_inline bool yyjson_is_null(yyjson_val *val)
Definition: yyjson.h:3472
yyjson_api_inline bool yyjson_is_sint(yyjson_val *val)
Definition: yyjson.h:3492
yyjson_api_inline bool yyjson_is_uint(yyjson_val *val)
Definition: yyjson.h:3488
yyjson_api_inline bool yyjson_is_arr(yyjson_val *val)
Definition: yyjson.h:3512
yyjson_api_inline bool yyjson_is_num(yyjson_val *val)
Definition: yyjson.h:3504
yyjson_api_inline bool yyjson_is_obj(yyjson_val *val)
Definition: yyjson.h:3516
JSON Value Content API
Returns the content or type of a JSON value.
This set of APIs also have version for mutable values, see mutable and immutable for details.
Returns value's type.
uint8_t yyjson_type
Definition: yyjson.h:430
yyjson_api_inline yyjson_type yyjson_get_type(yyjson_val *val)
Definition: yyjson.h:3530
Returns value's subtype.
uint8_t yyjson_subtype
Definition: yyjson.h:441
yyjson_api_inline yyjson_subtype yyjson_get_subtype(yyjson_val *val)
Definition: yyjson.h:3534
Returns value's tag.
yyjson_api_inline uint8_t yyjson_get_tag(yyjson_val *val)
Definition: yyjson.h:3538
Returns type description, such as: "null", "string", "array", "object", "true", "false", "uint", "sint", "real", "unknown"
yyjson_api_inline const char * yyjson_get_type_desc(yyjson_val *val)
Definition: yyjson.h:3542
Returns bool value, or false if the value is not bool type.
yyjson_api_inline bool yyjson_get_bool(yyjson_val *val)
Definition: yyjson.h:3562
Returns uint value, or 0 if the value is not uint type.
yyjson_api_inline uint64_t yyjson_get_uint(yyjson_val *val)
Definition: yyjson.h:3566
Returns sint value, or 0 if the value is not sint type.
yyjson_api_inline int64_t yyjson_get_sint(yyjson_val *val)
Definition: yyjson.h:3570
Returns int value (uint may overflow), or 0 if the value is not uint or sint type.
yyjson_api_inline int yyjson_get_int(yyjson_val *val)
Definition: yyjson.h:3574
Returns double value, or 0 if the value is not real type.
yyjson_api_inline double yyjson_get_real(yyjson_val *val)
Definition: yyjson.h:3578
Returns the string value, or NULL if the value is not string type
yyjson_api_inline const char * yyjson_get_str(yyjson_val *val)
Definition: yyjson.h:3582
Returns the string's length, or 0 if the value is not string type.
yyjson_api_inline size_t yyjson_get_len(yyjson_val *val)
Definition: yyjson.h:3586
Returns whether the value is equals to a string.
yyjson_api_inline bool yyjson_equals_str(yyjson_val *val, const char *str)
Definition: yyjson.h:3590
Same as `yyjson_equals_str(), but you can pass an explicit string length.
yyjson_api_inline bool yyjson_equals_strn(yyjson_val *val, const char *str, size_t len)
Definition: yyjson.h:3597
JSON Array API
Returns the property or child value of a JSON array.
This set of APIs also have version for mutable values, see mutable and immutable for details.
Returns the number of elements in this array, or 0 if the input is not an array.
yyjson_api_inline size_t yyjson_arr_size(yyjson_val *arr)
Definition: yyjson.h:3620
Returns the element at the specified position in this array, or NULL if array is empty or the index is out of bounds.
Note that this function takes a linear search time if array is not flat.
yyjson_api_inline yyjson_val * yyjson_arr_get(yyjson_val *arr, size_t idx)
Definition: yyjson.h:3624
Returns the first element of this array, or NULL if array is empty.
yyjson_api_inline yyjson_val * yyjson_arr_get_first(yyjson_val *arr)
Definition: yyjson.h:3639
Returns the last element of this array, or NULL if array is empty.
Note tha this function takes a linear search time if array is not flat.
yyjson_api_inline yyjson_val * yyjson_arr_get_last(yyjson_val *arr)
Definition: yyjson.h:3648
JSON Array Iterator API
You can use two methods to traverse an array:
Sample code (iterator):
print(val);
}
yyjson_api_inline bool yyjson_arr_iter_init(yyjson_val *arr, yyjson_arr_iter *iter)
Definition: yyjson.h:3676
yyjson_api_inline yyjson_val * yyjson_arr_iter_next(yyjson_arr_iter *iter)
Definition: yyjson.h:3692
Definition: yyjson.h:3670
Sample code (foreach):
size_t idx, max;
print(idx, val);
}
#define yyjson_arr_foreach(arr, idx, max, val)
Definition: yyjson.h:1440
There's also mutable version API to traverse an mutable array:
Sample code (mutable iterator):
if (val_is_unused(val)) {
}
}
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_iter_remove(yyjson_mut_arr_iter *iter)
Definition: yyjson.h:4316
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_iter_next(yyjson_mut_arr_iter *iter)
Definition: yyjson.h:4304
yyjson_api_inline bool yyjson_mut_arr_iter_init(yyjson_mut_val *arr, yyjson_mut_arr_iter *iter)
Definition: yyjson.h:4286
Definition: yyjson.h:4278
Sample code (mutable foreach):
size_t idx, max;
print(idx, val);
}
#define yyjson_mut_arr_foreach(arr, idx, max, val)
Definition: yyjson.h:1989
JSON Object API
Returns the property or child value of a JSON object.
This set of APIs also have version for mutable values, see mutable and immutable for details.
Returns the number of key-value pairs in this object, or 0 if input is not an object.
yyjson_api_inline size_t yyjson_obj_size(yyjson_val *obj)
Definition: yyjson.h:3709
Returns the value to which the specified key is mapped,
or NULL if this object contains no mapping for the key.
Note that this function takes a linear search time.
yyjson_api_inline yyjson_val * yyjson_obj_get(yyjson_val *obj, const char *key)
Definition: yyjson.h:3713
Same as `yyjson_obj_get(), but you can pass an explicit string length.
yyjson_api_inline yyjson_val * yyjson_obj_getn(yyjson_val *obj, const char *key, size_t key_len)
Definition: yyjson.h:3718
If the order of object's key is known at compile-time, you can use this method to avoid searching the entire object:
}
yyjson_api_inline yyjson_val * yyjson_obj_iter_get(yyjson_obj_iter *iter, const char *key)
Definition: yyjson.h:3780
yyjson_api_inline bool yyjson_obj_iter_init(yyjson_val *obj, yyjson_obj_iter *iter)
Definition: yyjson.h:3749
Definition: yyjson.h:3742
JSON Object Iterator API
You can use two methods to traverse an object:
Sample code (iterator):
print(key, val);
}
yyjson_api_inline yyjson_val * yyjson_obj_iter_get_val(yyjson_val *key)
Definition: yyjson.h:3776
yyjson_api_inline yyjson_val * yyjson_obj_iter_next(yyjson_obj_iter *iter)
Definition: yyjson.h:3766
Sample code (foreach):
size_t idx, max;
print(key, val);
}
#define yyjson_obj_foreach(obj, idx, max, key, val)
Definition: yyjson.h:1597
There's also mutable version API to traverse an mutable object:
Sample code (mutable iterator):
if (key_is_unused(key)) {
}
}
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_iter_next(yyjson_mut_obj_iter *iter)
Definition: yyjson.h:4944
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_iter_remove(yyjson_mut_obj_iter *iter)
Definition: yyjson.h:4961
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_iter_get_val(yyjson_mut_val *key)
Definition: yyjson.h:4956
yyjson_api_inline bool yyjson_mut_obj_iter_init(yyjson_mut_val *obj, yyjson_mut_obj_iter *iter)
Definition: yyjson.h:4926
Definition: yyjson.h:4918
Sample code (mutable foreach):
size_t idx, max;
print(key, val);
}
JSON Pointer
yyjson
allows you to query JSON value with JSON Pointer
(RFC 6901).
yyjson_api_inline yyjson_val * yyjson_get_pointer(yyjson_val *val, const char *ptr)
Definition: yyjson.h:5476
yyjson_api_inline yyjson_mut_val * yyjson_mut_get_pointer(yyjson_mut_val *val, const char *ptr)
Definition: yyjson.h:5502
yyjson_api_inline yyjson_mut_val * yyjson_mut_doc_get_pointer(yyjson_mut_doc *doc, const char *ptr)
Definition: yyjson.h:5513
yyjson_api_inline yyjson_mut_val * yyjson_mut_doc_get_pointern(yyjson_mut_doc *doc, const char *ptr, size_t len)
Definition: yyjson.h:5508
yyjson_api_inline yyjson_val * yyjson_doc_get_pointern(yyjson_doc *doc, const char *ptr, size_t len)
Definition: yyjson.h:5482
yyjson_api_inline yyjson_val * yyjson_get_pointern(yyjson_val *val, const char *ptr, size_t len)
Definition: yyjson.h:5467
yyjson_api_inline yyjson_mut_val * yyjson_mut_get_pointern(yyjson_mut_val *val, const char *ptr, size_t len)
Definition: yyjson.h:5493
yyjson_api_inline yyjson_val * yyjson_doc_get_pointer(yyjson_doc *doc, const char *ptr)
Definition: yyjson.h:5488
For example, given the JSON document:
{
"size" : 3,
"users" : [
{"id": 1, "name": "Harry"},
{"id": 2, "name": "Ron"},
{"id": 3, "name": "Hermione"}
]
}
The following JSON strings evaluate to the accompanying values:
Pointer | Matched Value |
"" | the whole document |
"/size" | 3 |
"/users/0" | {"id": 1, "name": "Harry"} |
"/users/1/name" | "Ron" |
"/no_match" | NULL |
"no_slash" | NULL |
Create JSON Document
You can use a yyjson_mut_doc
to build your JSON document.
Notice that yyjson_mut_doc
use a memory pool to hold all strings and values; the pool can only be created, grown or freed in its entirety. Thus yyjson_mut_doc
is more suitable for write-once, than mutation of an existing document.
Sample code:
yyjson_api void yyjson_mut_doc_free(yyjson_mut_doc *doc)
yyjson_api_inline yyjson_mut_val * yyjson_mut_uint(yyjson_mut_doc *doc, uint64_t num)
Definition: yyjson.h:4151
yyjson_api_inline bool yyjson_mut_arr_append(yyjson_mut_val *arr, yyjson_mut_val *val)
Definition: yyjson.h:4560
Mutable Document API
Creates and returns a new mutable JSON document, returns NULL on error.
If allocator is NULL, the default allocator will be used. The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
Delete the JSON document, free the memory of this doc (and all values created from this doc).
Get or set the root value of this JSON document.
yyjson_api_inline yyjson_mut_val * yyjson_mut_doc_get_root(yyjson_mut_doc *doc)
Definition: yyjson.h:3915
Copies and returns a new mutable document from input, returns NULL on error.
The alc
is memory allocator, pass NULL if you don't need it, see memory allocator for details.
yyjson_api yyjson_mut_doc * yyjson_doc_mut_copy(yyjson_doc *doc, const yyjson_alc *alc)
Copies and returns a new mutable value from input, returns NULL on error.
The memory was managed by document. */
yyjson_api yyjson_mut_val * yyjson_val_mut_copy(yyjson_mut_doc *doc, yyjson_val *val)
Mutable JSON Value Creation API
You can use these functions to create mutable JSON value,
The value's memory is held by the document.
Creates and returns a null value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_null(yyjson_mut_doc *doc)
Definition: yyjson.h:4106
Creates and returns a true value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_true(yyjson_mut_doc *doc)
Definition: yyjson.h:4117
Creates and returns a false value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_false(yyjson_mut_doc *doc)
Definition: yyjson.h:4128
Creates and returns a bool value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_bool(yyjson_mut_doc *doc, bool val)
Definition: yyjson.h:4139
Creates and returns an unsigned integer value, returns NULL on error.
Creates and returns a signed integer value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_sint(yyjson_mut_doc *doc, int64_t num)
Definition: yyjson.h:4164
Creates and returns a signed integer value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_int(yyjson_mut_doc *doc, int64_t num)
Definition: yyjson.h:4177
Creates and returns an real number value, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_real(yyjson_mut_doc *doc, double num)
Definition: yyjson.h:4182
Creates and returns a string value, returns NULL on error.
The input value should be a valid UTF-8 encoded string with null-terminator.
Note that the input string is NOT copied.
yyjson_api_inline yyjson_mut_val * yyjson_mut_str(yyjson_mut_doc *doc, const char *str)
Definition: yyjson.h:4195
Creates and returns a string value, returns NULL on error.
The input value should be a valid UTF-8 encoded string.
Note that the input string is NOT copied.
yyjson_api_inline yyjson_mut_val * yyjson_mut_strn(yyjson_mut_doc *doc, const char *str, size_t len)
Definition: yyjson.h:4201
Creates and returns a string value, returns NULL on error.
The input value should be a valid UTF-8 encoded string with null-terminator.
The input string is copied and held by the document.
yyjson_api_inline yyjson_mut_val * yyjson_mut_strcpy(yyjson_mut_doc *doc, const char *str)
Definition: yyjson.h:4215
Creates and returns a string value, returns NULL on error.
The input value should be a valid UTF-8 encoded string.
The input string is copied and held by the document.
yyjson_api_inline yyjson_mut_val * yyjson_mut_strncpy(yyjson_mut_doc *doc, const char *str, size_t len)
Definition: yyjson.h:4221
Mutable JSON Array Creation API
Creates and returns an empty mutable array, returns NULL on error.
Creates and returns a mutable array with c array.
int vals[3] = {-1, 0, 1};
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_sint(yyjson_mut_doc *doc, const int64_t *vals, size_t count)
Definition: yyjson.h:4378
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_uint8(yyjson_mut_doc *doc, const uint8_t *vals, size_t count)
Definition: yyjson.h:4425
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_sint64(yyjson_mut_doc *doc, const int64_t *vals, size_t count)
Definition: yyjson.h:4417
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_float(yyjson_mut_doc *doc, const float *vals, size_t count)
Definition: yyjson.h:4457
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_sint32(yyjson_mut_doc *doc, const int32_t *vals, size_t count)
Definition: yyjson.h:4409
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_real(yyjson_mut_doc *doc, const double *vals, size_t count)
Definition: yyjson.h:4388
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_sint16(yyjson_mut_doc *doc, const int16_t *vals, size_t count)
Definition: yyjson.h:4401
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_uint16(yyjson_mut_doc *doc, const uint16_t *vals, size_t count)
Definition: yyjson.h:4433
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_uint64(yyjson_mut_doc *doc, const uint64_t *vals, size_t count)
Definition: yyjson.h:4449
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_uint(yyjson_mut_doc *doc, const uint64_t *vals, size_t count)
Definition: yyjson.h:4383
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_sint8(yyjson_mut_doc *doc, const int8_t *vals, size_t count)
Definition: yyjson.h:4393
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_uint32(yyjson_mut_doc *doc, const uint32_t *vals, size_t count)
Definition: yyjson.h:4441
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_double(yyjson_mut_doc *doc, const double *vals, size_t count)
Definition: yyjson.h:4465
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_bool(yyjson_mut_doc *doc, const bool *vals, size_t count)
Definition: yyjson.h:4371
Creates and returns a mutable array with strings. The strings should be encoded as UTF-8.
const char strs[3] = {"Jan", "Feb", "Mar"};
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_strn(yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count)
Definition: yyjson.h:4483
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_strcpy(yyjson_mut_doc *doc, const char **vals, size_t count)
Definition: yyjson.h:4493
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_strncpy(yyjson_mut_doc *doc, const char **vals, const size_t *lens, size_t count)
Definition: yyjson.h:4507
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_with_str(yyjson_mut_doc *doc, const char **vals, size_t count)
Definition: yyjson.h:4473
Mutable JSON Array Modification API
Inserts a value into an array at a given index, returns false on error.
Note that Tthis function takes a linear search time.
yyjson_api_inline bool yyjson_mut_arr_insert(yyjson_mut_val *arr, yyjson_mut_val *val, size_t idx)
Definition: yyjson.h:4529
Inserts a val at the end of the array, returns false on error.
Inserts a val at the head of the array, returns false on error.
yyjson_api_inline bool yyjson_mut_arr_prepend(yyjson_mut_val *arr, yyjson_mut_val *val)
Definition: yyjson.h:4579
Replaces a value at index and returns old value, returns NULL on error.
Note that this function takes a linear search time.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_replace(yyjson_mut_val *arr, size_t idx, yyjson_mut_val *val)
Definition: yyjson.h:4598
Removes and returns a value at index, returns NULL on error.
Note that this function takes a linear search time.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_remove(yyjson_mut_val *arr, size_t idx)
Definition: yyjson.h:4626
Removes and returns the first value in this array, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_remove_first(yyjson_mut_val *arr)
Definition: yyjson.h:4650
Removes and returns the last value in this array, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_remove_last(yyjson_mut_val *arr)
Definition: yyjson.h:4669
Removes all values within a specified range in the array.
Note that this function takes a linear search time.
yyjson_api_inline bool yyjson_mut_arr_remove_range(yyjson_mut_val *arr, size_t idx, size_t len)
Definition: yyjson.h:4691
Removes all values in this array.
yyjson_api_inline bool yyjson_mut_arr_clear(yyjson_mut_val *arr)
Definition: yyjson.h:4713
Mutable JSON Array Modification Convenience API
Adds a value at the end of this array, returns false on error.
yyjson_api_inline bool yyjson_mut_arr_add_str(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *str)
Definition: yyjson.h:4821
yyjson_api_inline bool yyjson_mut_arr_add_true(yyjson_mut_doc *doc, yyjson_mut_val *arr)
Definition: yyjson.h:4753
yyjson_api_inline bool yyjson_mut_arr_add_strncpy(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *str, size_t len)
Definition: yyjson.h:4851
yyjson_api_inline bool yyjson_mut_arr_add_strcpy(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *str)
Definition: yyjson.h:4841
yyjson_api_inline bool yyjson_mut_arr_add_bool(yyjson_mut_doc *doc, yyjson_mut_val *arr, bool val)
Definition: yyjson.h:4771
yyjson_api_inline bool yyjson_mut_arr_add_uint(yyjson_mut_doc *doc, yyjson_mut_val *arr, uint64_t num)
Definition: yyjson.h:4781
yyjson_api_inline bool yyjson_mut_arr_add_false(yyjson_mut_doc *doc, yyjson_mut_val *arr)
Definition: yyjson.h:4762
yyjson_api_inline bool yyjson_mut_arr_add_strn(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *str, size_t len)
Definition: yyjson.h:4831
yyjson_api_inline bool yyjson_mut_arr_add_real(yyjson_mut_doc *doc, yyjson_mut_val *arr, double num)
Definition: yyjson.h:4811
yyjson_api_inline bool yyjson_mut_arr_add_val(yyjson_mut_val *arr, yyjson_mut_val *val)
Definition: yyjson.h:4739
yyjson_api_inline bool yyjson_mut_arr_add_sint(yyjson_mut_doc *doc, yyjson_mut_val *arr, int64_t num)
Definition: yyjson.h:4791
yyjson_api_inline bool yyjson_mut_arr_add_null(yyjson_mut_doc *doc, yyjson_mut_val *arr)
Definition: yyjson.h:4744
Creates and adds a new array at the end of the array.
Returns the new array, or NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_add_arr(yyjson_mut_doc *doc, yyjson_mut_val *arr)
Definition: yyjson.h:4861
Creates and adds a new object at the end of the array.
Returns the new object, or NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_arr_add_obj(yyjson_mut_doc *doc, yyjson_mut_val *arr)
Definition: yyjson.h:4870
Mutable JSON Object Creation API
Creates and returns a mutable object, returns NULL on error.
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj(yyjson_mut_doc *doc)
Definition: yyjson.h:5011
Creates and returns a mutable object with keys and values,
returns NULL on error. The keys and values are NOT copied.
The strings should be encoded as UTF-8 with null-terminator.
const char **keys,
const char **vals,
size_t count);
const char vkeys[] = {"name", "type", "id"};
const char *vals[] = {"Harry", "student", "888999"};
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_with_str(yyjson_mut_doc *doc, const char **keys, const char **vals, size_t count)
Definition: yyjson.h:5022
Creates and returns a mutable object with key-value pairs and pair count,
returns NULL on error. The keys and values are NOT copied.
The strings should be encoded as UTF-8 with null-terminator.
const char **kv_pairs,
size_t pair_count);
const char *pairs[] = {"name", "Harry", "type", "student", "id", "888999"};
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_with_kv(yyjson_mut_doc *doc, const char **kv_pairs, size_t pair_count)
Definition: yyjson.h:5053
Mutable JSON Object Modification API
Adds a key-value pair at the end of the object. The key must be a string.
This function allows duplicated key in one object.
bool yyjson_mut_obj_add(yyjson_mut_val *obj, yyjson_mut_val *key,yyjson_mut_val *val);
Adds a key-value pair to the object, The key must be a string.
This function may remove all key-value pairs for the given key before add.
Note that this function takes a linear search time.
yyjson_api_inline bool yyjson_mut_obj_put(yyjson_mut_val *obj, yyjson_mut_val *key, yyjson_mut_val *val)
Definition: yyjson.h:5178
Removes key-value pair from the object with given key.
Note that this function takes a linear search time.
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_remove(yyjson_mut_val *obj, yyjson_mut_val *key)
Definition: yyjson.h:5216
Removes all key-value pairs in this object.
yyjson_api_inline bool yyjson_mut_obj_clear(yyjson_mut_val *obj)
Definition: yyjson.h:5245
Mutable JSON Object Modification Convenience API
Adds a key-value pair at the end of the object. The key is not copied.
Note that these functions allow duplicated key in one object.
yyjson_api_inline bool yyjson_mut_obj_add_strncpy(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val, size_t len)
Definition: yyjson.h:5404
yyjson_api_inline bool yyjson_mut_obj_add_sint(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, int64_t val)
Definition: yyjson.h:5338
yyjson_api_inline bool yyjson_mut_obj_add_strn(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val, size_t len)
Definition: yyjson.h:5379
yyjson_api_inline bool yyjson_mut_obj_add_false(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key)
Definition: yyjson.h:5311
yyjson_api_inline bool yyjson_mut_obj_add_int(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, int64_t val)
Definition: yyjson.h:5348
yyjson_api_inline bool yyjson_mut_obj_add_uint(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, uint64_t val)
Definition: yyjson.h:5328
yyjson_api_inline bool yyjson_mut_obj_add_null(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key)
Definition: yyjson.h:5295
yyjson_api_inline bool yyjson_mut_obj_add_true(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key)
Definition: yyjson.h:5303
yyjson_api_inline bool yyjson_mut_obj_add_str(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val)
Definition: yyjson.h:5368
yyjson_api_inline bool yyjson_mut_obj_add_real(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, double val)
Definition: yyjson.h:5358
yyjson_api_inline bool yyjson_mut_obj_add_bool(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, bool val)
Definition: yyjson.h:5319
yyjson_api_inline bool yyjson_mut_obj_add_strcpy(yyjson_mut_doc *doc, yyjson_mut_val *obj, const char *key, const char *val)
Definition: yyjson.h:5391
Removes all key-value pairs for the given key.
Note that this function takes a linear search time.
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_remove_str(yyjson_mut_val *obj, const char *key)
Definition: yyjson.h:5427
yyjson_api_inline yyjson_mut_val * yyjson_mut_obj_remove_strn(yyjson_mut_val *obj, const char *key, size_t len)
Definition: yyjson.h:5432
JSON Merge Patch
Creates and returns a merge-patched JSON value (RFC 7386). Returns NULL if the patch could not be applied. Specification and example: https://tools.ietf.org/html/rfc7386
yyjson_api yyjson_mut_val * yyjson_merge_patch(yyjson_mut_doc *doc, yyjson_val *orig, yyjson_val *patch)
Number Processing
Number reader
yyjson has a built-in high-performance number reader,
it will parse numbers according to these rules by default:
- Read positive integer as
uint64_t
, if overflow, convert to double
.
- Read negative integer as
int64_t
, if overflow, convert to double
.
- Read floating-point number as
double
with correct rounding (no ulp error).
- If a
real
number overflow (infinity), it will report an error.
- If a number does not match the JSON standard, it will report an error.
You can use YYJSON_READ_ALLOW_INF_AND_NAN
flag to allow nan
and inf
number/literal, see reader flag for details.
Number writer
yyjson has a built-in high-performance number writer,
it will write numbers according to these rules by default:
- Write positive integer without sign.
- Write negative integer with a negative sign.
- Write floating-point number with ECMAScript format, but with the following changes:
- If number is
Infinity
or NaN
, report an error.
- Keep the negative sign of 0.0 to preserve input information.
- Remove positive sign of exponent part.
- Floating-point number writer should generate shortest correctly rounded decimal representation.
You can use YYJSON_WRITE_ALLOW_INF_AND_NAN
flag to write inf/nan number as Infinity
and NaN
literals without error, but this is not standard JSON, see writer flag for details.
You can also use YYJSON_WRITE_INF_AND_NAN_AS_NULL
to write inf/nan number as null
without error.
Text Processing
Character Encoding
yyjson only supports UTF-8 encoding without BOM, as specified in RFC 8259:
JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8. Implementations MUST NOT add a byte order mark (U+FEFF) to the beginning of a networked-transmitted JSON text.
By default, yyjson performs a strict UTF-8 encoding validation on input strings. An error will be reported when an invalid character is encountered.
You could use YYJSON_READ_ALLOW_INVALID_UNICODE
and YYJSON_WRITE_ALLOW_INVALID_UNICODE
flag to allow invalid unicode encoding. However, you should be aware that the result value from yyjson may contain invalid characters, which can be used by other code and may pose security risks.
NUL Character
yyjson supports the NUL
character (also known as null terminator
, or Unicode U+0000
, ASCII \0
).
When reading JSON, \u0000
will be unescaped to NUL
. If a string contains NUL
, the length obtained with strlen() will be inaccurate, and you should use yyjson_get_len() to get the real length.
When building JSON, the input string is treated as null-terminated. If you need to pass in a string with NUL
inside, you should use the API with the n
suffix and pass in the real length.
For example:
Memory Allocator
yyjson does not call libc's memory allocation functions (malloc/realloc/free) directly. When memory allocation is required, yyjson's API takes a parameter named alc
that allows the caller to pass in an allocator. If the alc
is NULL, yyjson will use the default memory allocator, which is a simple wrapper of libc's functions.
Custom memory allocator allows you to take more control over memory allocation, here are a few examples:
Single allocator for multiple JSON
If you need to parse multiple small JSON, you can use a single allocator with pre-allocated buffer to avoid frequent memory allocation.
Sample code:
size_t max_json_size = 64 * 1024;
void *buf = malloc(buf_size);
for(int i = 0, i < your_json_file_count; i++) {
const char *your_json_file_path = ...;
...
}
free(buf);
yyjson_api_inline size_t yyjson_read_max_memory_usage(size_t len, yyjson_read_flag flg)
Definition: yyjson.h:782
Stack memory allocator
If the JSON is small enough, you can use stack memory to read or write it.
Sample code:
char buf[128 * 1024];
...
yyjson_doc_free(doc);
Use third-party allocator library
You can use a third-party high-performance memory allocator for yyjson,
such as jemalloc, tcmalloc, mimalloc.
Sample code:
#include <mimalloc.h>
static void *priv_malloc(void *ctx, size_t size) {
return mi_malloc(size);
}
static void *priv_realloc(void *ctx, void *ptr, size_t size) {
return mi_realloc(ptr, size);
}
static void priv_free(void *ctx, void *ptr) {
mi_free(ptr);
}
priv_malloc,
priv_realloc,
priv_free,
NULL
};
yyjson_doc *doc = yyjson_doc_read_opts(dat, len, 0, &PRIV_ALC, NULL);
...
yyjson_doc_free(doc);
char *json = yyjson_doc_write(doc, 0, alc, NULL, NULL);
...
alc->free(alc->
ctx, json);
Mutable and Immutable
yyjson have 2 types of data structures: immutable and mutable:
When reading a JSON, yyjson returns immutable document and values;
When building a JSON, yyjson creates mutable document and values.
yyjson also provides some methods to convert immutable document into mutable document:
For most immutable APIs, you can just add a mut
prefix to get the mutable version, for example:
yyjson_api_inline yyjson_type yyjson_mut_get_type(yyjson_mut_val *val)
Definition: yyjson.h:3992
yyjson_api_inline bool yyjson_mut_is_str(yyjson_mut_val *val)
Definition: yyjson.h:3970
See data structure for more details.
Null Check
yyjson
's public API will do null check
for every input parameters to avoid crashes.
For example, when reading a JSON, you don't need to do null check or type check on each value:
if (!str) printf("err!");
But if you are sure that a value is non-null, and the type is matched, you can use the unsafe
prefix API to avoid the null check.
For example, when iterating over an array or object, the value and key must be non-null:
size_t idx, max;
if (unsafe_yyjson_equals_str(key, "id") &&
unsafe_yyjson_is_uint(val) &&
unsafe_yyjson_get_uint(val) == 1234) {
}
}
Thread Safe
yyjson does not use global variables, so if you can ensure that the input parameters of a function are immutable, then the function call is thread-safe.
yyjson_doc
and yyjson_val
is immutable and thread-safe,
yyjson_mut_doc
and yyjson_mut_val
is mutable and not thread-safe.
Locale Dependent
yyjson is locale-independent.
However, there are some special conditions that you need to be aware of:
- You use libc's
setlocale()
function to change locale.
- Your environment does not use IEEE 754 floating-point (e.g. some IBM mainframes) or you explicitly specified the
YYJSON_DISABLE_FAST_FP_CONV
flag at build time.
When you meet both of these conditions, you should avoid call setlocale()
while other thread is parsing JSON, otherwise an error may be returned for JSON floating point number parsing.