LJSON

中文版
LJSON in One Sentence
LJSON is one library with two engines: a fully-featured JSON5-compliant JSON engine, and one of the fastest bidirectional number↔string conversion engines available.
It is written in pure C99, has zero third-party dependencies, and depends on no CPU-specific features (no SIMD, no inline assembly) — yet it lands in the fastest tier among general-purpose, editable JSON libraries. That is because its performance comes entirely from algorithms, data structures, and engineering trade-offs, not from squeezing a particular instruction set.
Why LJSON: Ten Things to Read First
If you only have 30 seconds to decide whether to keep reading, this table is enough. By “general-purpose library” we mean: it can both parse and print, it is editable and reusable, and it handles everything from tiny messages to multi-GB files — as opposed to a specialized library that pushes a single metric to the extreme and nothing else.
This chapter is a quick overview: one line per item, covering “what it is” and “what it does for you”.
The technical details and measurements behind each item are expanded in Chapter 2: Key Features, Chapter 6: Performance Benchmarks, and Chapter 7: Why LJSON Is So Fast.
| # |
Selling point |
What LJSON does |
What it means for you |
| 1 |
Pure C99, zero dependencies |
Only standard headers such as <string.h> / <stdlib.h> / <stdio.h>; two files jnum.c and json.c are enough to build |
Works on embedded, RTOS, bare metal, cross-compilation; builds very fast |
| 2 |
No CPU-feature dependency |
No SIMD, no inline assembly; every compiler intrinsic used (__builtin_clzll, _umul128, __int128) has a portable C fallback |
Change architecture without changing code; consistent on ARM/x86/RISC-V/MIPS |
| 3 |
Unified C11 generic interface |
json_create_unit / json_create_units / json_set_number / json_sax_print_array_item dispatch by type via _Generic; automatically switches to overloads under C++ |
One API for bool/int32/uint32/int64/uint64/double/string/binary — feels like a dynamic language |
| 4 |
7 parse modes |
Classic DOM / memory-pool DOM / reuse DOM / file-stream DOM / file-stream + memory-pool DOM / SAX / SAX file-stream |
Small messages, large files, read-only scanning, editable trees — each has an optimal answer, no compromise for all |
| 5 |
4 print modes |
DOM→string, DOM→file (true streaming), SAX→string, SAX→file (true streaming) |
Printing a huge JSON never requires materializing the whole string first; memory can stay constant |
| 6 |
True streaming |
Parses while reading, writes while printing — not the fake “read it all, then parse / print it all, then write” |
A 1 GB JSON can be reformatted with KB-level memory |
| 7 |
Editable and zero-copy |
Reuse mode (mode 3) reuses the original string in place and stays natively editable (yyjson needs an extra conversion, doubling memory) |
For “fast but also mutable” workloads, LJSON is one of the few viable answers |
| 8 |
Zero heap allocation |
After the first allocation, the library performs no heap allocation at all during the parse/print loop |
High-frequency message handling with no fragmentation, no allocation jitter, predictable latency |
| 9 |
In-house ldouble numeric engine |
float→string takes about 0.25%~10% of snprintf (10~390× faster on individual v5.0.6 cases); string→number is 2~19× faster than strtod |
Float-heavy JSON (geospatial, time series) gains an order of magnitude in print performance |
| 10 |
Engineering maintainability |
About 10k lines, clear structure, bilingual (Chinese/English) comments on every API; API style modeled on cJSON |
Readable, modifiable, extensible — not a black box you can only admire |
In one sentence: LJSON is not “the library that is fastest in one particular mode” — it is “the library that lets you pick a near-optimal path for any scenario, while still being faster than most libraries on that path.”
1. Project Positioning
1.1 Dual-Mode Engine: One Library, Two Engines
LJSON ships two engines in one repository. They can be used independently or work together deeply:
| Engine |
Source |
Header |
Responsibility |
Usable standalone |
| JSON engine |
json.c |
json.h |
Parsing and generating JSON5 text: DOM / SAX dual paradigm, true streaming file I/O, memory pool, in-place reuse, zero-heap allocation, json_items access acceleration, prev access acceleration |
✅ |
| Numeric engine (jnum) |
jnum.c |
jnum.h |
Bidirectional high-speed number↔string conversion: integers / long integers / hex / double, with the in-house ldouble algorithm |
✅ just compile jnum.c |
How the two work together: every number printed as JSON goes through a “number → string” conversion. LJSON does not call sprintf; the print path calls its own jnum_dtoa directly. That single decision is the direct reason print performance on float-heavy data (such as canada.json) beats cJSON by an order of magnitude.
1.2 What “General-Purpose and Fastest” Means
LJSON is positioned as a general-purpose JSON library, not a benchmark-specialized one. Its objective function balances five variables at once:
performance + memory footprint + editability + streaming + maintainability
This explains how it differs from the “extremist” libraries:
- Extremists (e.g. yyjson’s read-only mode): push one point to the extreme, at the cost of giving up streaming, giving up in-place editability, giving up standard C strings, giving up code readability.
- LJSON: provides a complete mode matrix so every scenario can match a near-optimal path, while still winning on the general-purpose editable path.
Its architectural philosophy in one sentence:
There is no absolutely optimal mode, only the most suitable mode.
Rather than compromise by forcing every scenario into a single implementation, hand the choice to the user — but make sure every choice is still fast.
1.3 Version and Compatibility
- Current version: v5.x
- Born: October 2019
- Important compatibility note: on 64-bit systems, starting from v5.0.0, the JSON object was shrunk from 40 bytes to 32 bytes, improving parse speed by 5%~10%, and is not compatible with v3.x.x. When upgrading from v3 to v5, update your calling code accordingly.
2. Key Features
2.1 JSON Engine Features
① Extremely fast parsing and printing
On three samples — 1000×twitter.json (603 MB), 1000×citm_catalog.json (1.7 GB), and 100×canada.json (215 MB) — LJSON’s reuse mode (mode 3, editable) leads cJSON / RapidJSON / yyjson across the board: 1.2~6.6× faster parsing, 1.1~23× faster printing. Full data and analysis are in Section 6.3: Latest Terminal Measurements and Chapter 8: Head-to-Head.
② Full JSON5 support (off by default for speed, enable on demand)
Supports hex numbers, comments, trailing commas, single-quoted/unquoted keys, special characters inside strings, NaN/Infinity, and other modern JSON features.
⚠️ Important: some JSON5 features significantly affect the parse hot path, so they are off by default (speed first). Set the corresponding macro to 1 in json.c and rebuild when you need them; see Section 5.5: Parse Configuration.
Among them, JSON_PARSE_SKIP_COMMENT (comments) and JSON_PARSE_SPECIAL_QUOTES (single-quoted/unquoted keys) are off by default and have the largest impact on speed.
③ True streaming file handling
- Parsing: parses while reading the file, not “read everything first”
- Printing: writes to the file while printing, not “print everything first”
- SAX + file streaming keeps memory at a constant level: even a 1 GB JSON file can be reformatted with KB-level memory
④ Multi-level memory management
| Level |
Approach |
Benefit |
| Classic allocation |
malloc / free per node |
General-purpose, individually freeable |
| Memory pool |
Big-block bump allocation |
No fragmentation, near-zero allocation cost |
| In-place string reuse |
Use the original buffer directly as the storage for keys and strings |
Zero copy; saves one memcpy and one malloc |
| Zero-heap-allocation loop |
Keep reusing after the first allocation |
Zero malloc inside the library during the loop; predictable latency |
⑤ Memory reuse (two meanings)
- The original data is directly used as the storage for keys and strings (in-place reuse)
- The same block of memory is reused across many parses and prints, so the library never needs to allocate on the heap
⑥ Extended data types
Besides standard JSON types: long integers (64-bit), hex numbers, and the binary data extension (format <len:data>).
⑦ Compact object
On 64-bit systems json_object was shrunk from 40 bytes to 32 bytes (since v5.0.0), improving parse speed by 5%~10%. See Section 7.8: Data Structures.
⑧ Developer friendly
- API designed with reference to cJSON, so migration cost is very low
- Pure C, no third-party library dependencies
- Supports gcc / clang / MSVC and other compilers; x86 / ARM / RISC-V and other architectures
- Every API carries bilingual (Chinese/English) comments
- C11
_Generic generic interfaces + C++ overloads: one API for all types
2.2 Numeric Engine (LDOUBLE) Features
String → number (atod)
- 2~19× faster than the standard
strtod across the v5.0.6 cases (4~18× by group mean)
Number → string (dtoa)
- Takes about 0.25%~10% of
snprintf, i.e. 10~390× faster on individual cases; group means are 12~59× on Linux and 20~268× on Windows
- 17 digits of precision, and always emits the shortest exact representation
- Faster than grisu2 in every A-J group by group mean (1.4~4.1×; up to 16.7× on an individual case); a few individual Linux cases are marginally slower
- Faster than dragonbox in every A-J group by group mean (1.2~1.7×; up to 3.1× on an individual case); a few individual cases are marginally slower
Note: to chase performance, LDOUBLE’s boundary handling pursues the shortest representation rather than mechanical round-to-even, so it does not fully conform to strict IEEE-754 round-trip conventions. If your scenario needs standard-library behavior, compile with -DJSON_DTOA_ALGORITHM=1 to switch back to sprintf.
Full grouped data and the six-panel chart are in Section 6.7.
2.3 Supported Data Types
json_type_t as defined in json.h:
| Type |
Meaning |
Value member |
Notes |
JSON_NULL |
null |
— |
no value member |
JSON_BOOL |
true / false |
vnum.vbool |
|
JSON_INT |
32-bit signed integer |
vnum.vint |
|
JSON_HEX |
32-bit unsigned hex |
vnum.vhex |
extension, printed with 0x prefix |
JSON_LINT |
64-bit signed long integer |
vnum.vlint |
extension |
JSON_LHEX |
64-bit unsigned long hex |
vnum.vlhex |
extension, printed with 0x prefix |
JSON_DOUBLE |
double |
vnum.vdbl |
converted by the ldouble algorithm |
JSON_STRING |
string |
vstr + istr |
carries length and escape flag |
JSON_BINARY |
binary data |
vbin + istr |
extension, format <len:data> |
JSON_ARRAY |
array |
value.head |
list head |
JSON_OBJECT |
object |
value.head |
list head |
On the numeric engine side, jnum_type_t in jnum.h corresponds one-to-one (JNUM_NULL / JNUM_BOOL / JNUM_INT / JNUM_HEX / JNUM_LINT / JNUM_LHEX / JNUM_DOUBLE).
3. Architecture: 7 Parse Modes × 4 Print Modes
The core design of LJSON is a mode matrix: 7 parse modes and 4 print modes, freely combinable. Understand this matrix and you understand all of LJSON.
3.1 Seven Parse Modes
| Mode |
Name |
Core API |
Memory behavior |
Editable |
Typical scenario |
| 1 |
DOM classic mode |
json_parse_str |
malloc/free, allocated per node |
✅ |
General use, small JSON, free add/remove of nodes |
| 2 |
DOM memory-pool mode |
json_fast_parse_str |
big-block bump allocation, no fragmentation |
✅ |
Medium/large JSON, low allocation overhead |
| 3 |
DOM reuse mode ⭐ |
json_reuse_parse_str |
memory pool + in-place reuse of strings (zero copy) |
✅ |
High-frequency parsing, message buses, fast but also mutable |
| 4 |
DOM file-stream mode |
json_parse_file |
parses while reading, malloc allocation |
✅ |
Large files, avoid reading everything at once |
| 5 |
DOM file-stream + memory pool |
json_fast_parse_file |
parses while reading + memory pool |
✅ |
Large files + low allocation overhead |
| 6 |
SAX mode |
json_sax_parse_str |
callback driven, no full tree built |
— |
Only extraction/transformation needed, memory sensitive |
| 7 |
SAX file-stream mode ⭐ |
json_sax_parse_file |
parses while reading + callbacks |
— |
Constant memory for GB-level files |
The seven modes differ along only three dimensions
Don’t be intimidated by seven modes — the differences come from three orthogonal switches:
┌─ Build a DOM tree? ── DOM (1/2/3/4/5) vs SAX (6/7)
├─ Where does memory come from? ─ malloc (1/4) vs memory pool (2/3/5)
└─ Where does data come from? ─── string (1/2/3/6) vs file stream (4/5/7)
- DOM vs SAX: DOM builds the entire JSON tree so you can freely add, delete, modify and query; SAX only hands you events in callbacks, builds no tree, uses constant memory, but you never get “the whole tree”.
- malloc vs memory pool: the pool allocates one big block up front and then bumps a pointer internally (just add to a pointer); you cannot free an individual node, but you can free everything at once.
- String vs file stream: the file stream is true streaming — it parses while reading, with no need to load the whole file first.
Why is mode 3 (reuse mode) special?
It is the only mode that does all three of these at once:
- Uses a memory pool (near-zero allocation cost)
- Reuses strings in place from the original buffer (zero copy; saves one memcpy + one malloc)
- Stays editable (yyjson’s reuse mode is read-only; to edit you must convert another copy, doubling memory)
The cost: the original buffer is modified in place, and cannot be freed while the json is in use. That is also why it is the first choice for high-frequency message handling.
3.2 Four Print Modes
The four print modes
- DOM: from the json structure tree to a string
- DOM: from the json structure tree to a file, streaming (write while printing)
- SAX: directly from your data to a string
- SAX: directly from your data to a file, streaming (write while printing)
The generic DOM print interface is json_print_common(json, json_print_choice_t *choice); — the 4 specialized interfaces are:
| Mode |
DOM print API |
Description |
| DOM → string (formatted) |
json_print_format(json, item_total, &len, ptr) |
standard serialization |
| DOM → string (compact) |
json_print_unformat(json, item_total, &len, ptr) |
compact output |
| DOM → file (formatted, true streaming) |
json_fprint_format(json, item_total, path, ptr) |
prints while writing |
| DOM → file (compact, true streaming) |
json_fprint_unformat(json, item_total, path, ptr) |
prints while writing |
The common SAX printing trio (shared by all four modes)
| Stage |
API |
Role |
| Start |
json_sax_print_start(json_print_choice_t *choice) |
generic start; choice decides “string or file, formatted or compact” |
| Output |
json_sax_print_value(hd, type, jkey, value) |
generic output; values of every type go through it |
| Finish |
json_sax_print_finish(hd, length, ptr) |
wraps up; returns the string (when printing to string) or flushes the buffer (when printing to file) |
The four specialized SAX print start functions
The 4 starts below are all syntactic sugar over json_sax_print_start; they simply pre-fill format_flag and path in choice:
| Mode |
start API |
Equivalent to |
| 1 |
json_sax_print_format_start(item_total, ptr) |
choice.format_flag = true; choice.path = NULL; |
| 2 |
json_sax_print_unformat_start(item_total, ptr) |
choice.format_flag = false; choice.path = NULL; |
| 3 |
json_sax_fprint_format_start(item_total, path, ptr) |
choice.format_flag = true; choice.path = path; |
| 4 |
json_sax_fprint_unformat_start(item_total, path, ptr) |
choice.format_flag = false; choice.path = path; |
ptr (json_print_ptr_t) is used to reuse the print buffer: once passed in, results keep reusing ptr->p, and you only need to call json_memory_free(ptr->p) once at the end.
3.3 Mode Selection Guide
The conclusion first — just two rules:
Parsing: default to mode 3 (reuse mode).
Printing: default to SAX direct printing; do not build a DOM first.
Why default to mode 3 for parsing?
Mode 3 is LJSON’s own fastest parse path on all three datasets (twitter 320 ms vs mode 1’s 952 ms), and it is editable. Its only extra constraint is “the original buffer is modified and cannot be freed while in use” — for the normal flow of “receive a message → parse → handle it”, this constraint is almost always acceptable.
Only fall back to another mode in these cases:
| Situation |
Use instead |
| The original buffer must stay unmodified |
Mode 2 (memory pool; strings are copied) |
| You need to free individual nodes / hold part of the subtree long-term |
Mode 1 (classic malloc) |
| Data comes from a huge file and you don’t want to read it all at once |
Mode 5 (DOM needed) or mode 7 (no DOM) |
| You only need to extract a few fields from a huge file |
Mode 7 (SAX callbacks) |
Why default to SAX direct printing?
Because the DOM is an intermediate artifact. If your data already lives in your own structures (business objects, arrays, query results), then “build a DOM, then print from the DOM” is two entirely redundant conversions:
❌ your data → build DOM (N mallocs + linking) → walk DOM and print → delete DOM
✅ your data → SAX print (straight into the buffer)
SAX printing eliminates building and destroying the whole DOM tree; measured print throughput reaches 2.6~5.2 GB/s (see Section 6.4: Reuse Mode Throughput).
Only build a DOM first in these cases:
| Situation |
Use instead |
| The data already is a piece of JSON and you want to “read it, tweak it, output it” |
DOM parse + DOM print |
| You need random access by key, repeated edits, repeated prints |
DOM parse + DOM print |
| You need to reformat an existing JSON file |
Streaming mode 5/7, or json_fprint_format |
Strongly recommended combination: mode 3 parsing + SAX printing + zero heap allocation
This is LJSON’s standard answer for “high-frequency message send/receive”; the complete code is in Section 4.2: Recommended — The Zero-Heap-Allocation Mode. Its characteristics:
- Parsing reuses the memory pool
mem; printing reuses p of json_print_ptr_t
- Zero heap allocation inside the library during the loop
- Access is accelerated with
json_get_items, and json_items_t is reused as well
3.4 Mode Combination Matrix
Common combinations of parse mode × print mode:
| Scenario |
Parse |
Print |
Memory profile |
| High-frequency small messages (recommended) |
3 |
SAX→string |
zero heap allocation, constant memory |
| High-frequency small messages (to file) |
3 |
SAX→file |
zero heap allocation + true streaming write |
| Regular business JSON |
1 or 2 |
DOM→string |
one-shot, simple |
| Large-file reformatting (DOM needed) |
5 |
DOM→file |
streaming read + streaming write |
| Large-file reformatting (no DOM) |
7 |
SAX→file |
constant memory |
| Extracting fields from a large file |
7 |
custom (handle in callback) |
constant memory |
| Generating a very large JSON |
— |
SAX→file |
generate while writing |
| JSON to JSON (filter/rewrite) |
7 |
SAX→file |
parse and print on one pipeline |
The last row (SAX-printing directly inside the SAX parse callback) is exactly how mode 7 is implemented in json_test.c — it completes “read → parse → format → write” over the 1.7 GB citm_catalog.json with constant memory in 2946 ms.
4. Quick Start
4.1 Where to Find the API Documentation
The complete, authoritative API documentation lives in the two headers — json.h and jnum.h — where every API carries bilingual (Chinese/English) comments (parameter meaning, return value, caveats, usage advice). Just read them; no separate docs needed.
Memorize these naming rules and you will rarely need to look anything up:
| Prefix / suffix |
Meaning |
Example |
json_ |
classic interface (malloc allocation) |
json_create_int |
pjson_ |
memory-pool interface (extra json_mem_t *mem parameter) |
pjson_create_int |
json_create_xxx |
create an object of a given type |
json_create_double |
json_create_unit(s) |
C11 _Generic version; no need to remember type suffixes |
json_create_unit(3.14) |
json_add_xxx_to_array/object |
add a value of a given type |
json_add_string_to_object |
json_get_xxx_value |
read a value of a given type |
json_get_lint_value |
json_sax_print_xxx |
SAX-print one value |
json_sax_print_double |
json_fprint_xxx |
print to file (true streaming) |
json_fprint_format |
json_sax_fprint_xxx_start |
SAX print to file (true streaming) |
json_sax_fprint_format_start |
The runnable example collection lives in json_test.c: how to call all 7 parse modes, the full SAX printing flow, and the repeated parse/print pattern in reuse mode are all there.
The easiest pitfalls
| Caveat |
Explanation |
Parse APIs take char *, not const char * |
Reuse mode modifies the buffer in place (other modes don’t); never pass a string literal |
In memory-pool mode you cannot json_del_object per node |
Only pjson_memory_free(&mem) frees everything at once |
| In reuse mode the original buffer cannot be freed while in use |
Strings point directly into the original buffer |
json_string_t’s info must be filled |
Use json_string_info_update() to auto-fill len / escaped |
| The print buffer can be reused |
Pass json_print_ptr_t *ptr and free ptr->p only once at the end |
jnum_xxx needs a buffer of at least 27 bytes |
Stated explicitly in the header comments |
Every nesting level needs its own json_items_t |
They cannot be shared |
4.2 Recommended: The Zero-Heap-Allocation Mode
If your scenario is “loop parsing and printing small JSON” (high-frequency messaging, RPC, gateway forwarding), use this section’s pattern directly — don’t read anything else first.
Its key property: LJSON allocates memory only the first time; during subsequent processing the library performs no heap allocation at all — no fragmentation, no allocation jitter, predictable latency throughout the loop.
Four rules
- Keep reusing the memory pool
mem for storing json objects
- Reuse the original string for string values (i.e. the original string is modified, and cannot be freed while the json is in use)
- Use
json_get_items to speed up access to objects under JSON_ARRAY / JSON_OBJECT; its memory can be reused continuously (each level needs its own json_items_t)
- Keep reusing member
p of json_print_ptr_t for printing
size_t len = 0;
/* Initialization, done only once (parsing) */
json_mem_t mem;
pjson_memory_init(&mem);
/* obj_mgr needs a suitable value so that one memory block can hold all objects;
if the original string is not reused, the other 2 mgrs also need to be set */
mem.valid = true;
mem.obj_mgr.mem_size = max_data_size;
/* Reusable items for accelerated parsing */
json_items_t items;
memset(&items, 0, sizeof(items));
/* Initialization, done only once (printing) */
json_print_ptr_t ptr = {PRINT_BUF_LEN, 0};
/* The business loop */
while (1) {
/* ---- Receive message: JSON parsing ---- */
json_object *json = json_reuse_parse_str(buf, &len, &mem);
/* Get all data under some JSON_ARRAY */
if (json_get_items(array, &items) < 0)
return -1;
for (size_t i = 0; i < items.count; ++i) {
ids.push_back(json_get_lint_value(items.items[i].json));
}
/* ----- Business logic ---- */
/* ---- Send message: JSON printing ----*/
json_sax_print_hd hd = json_sax_print_unformat_start(100, &ptr); /* start printing (reuse ptr) */
json_sax_print_object(hd, NULL, JSON_SAX_START); /* top-level left brace */
/* Print data under some JSON_OBJECT */
json_sax_print_string(hd, &key, sval);
/* Print all data under some JSON_ARRAY */
json_sax_print_array(hd, &key, JSON_SAX_START);
for (const auto &v : ids) {
json_sax_print_lint(hd, NULL, v);
}
json_sax_print_array(hd, NULL, JSON_SAX_FINISH);
ret |= json_sax_print_object(hd, NULL, JSON_SAX_FINISH); /* top-level right brace */
json_sax_print_finish(hd, len, &ptr) /* finish printing; result is in ptr.p or the return value */
/* ----- JSON memory pool handling ---- */
/* The json structure is no longer needed; keep only the first list node */
pjson_memory_refresh(&mem);
}
/* Destroy resources, done only once (parsing) */
json_free_items(&items);
pjson_memory_free(&mem);
/* Destroy resources, done only once (printing) */
json_memory_free(ptr.p);
Why does this code achieve zero heap allocation? Three key points
mem.valid = true + obj_mgr.mem_size: tells LJSON “the pool already has usable memory, and one block can hold all objects”. Parsing then takes the bump path (pointer addition) and never triggers a new malloc.
pjson_memory_refresh(&mem): called at the end of each loop iteration, it keeps only the first memory-block node, frees the rest, and resets the write pointer back to the block start — so the next round allocates again from the beginning of the same block.
json_print_ptr_t ptr: the print buffer is reused for the whole loop; json_sax_print_finish(hd, len, &ptr) writes the resulting string back into ptr.p, which the next iteration keeps using.
Measured under this mode, the twitter sample reaches 2.71 GB/s parsing and 5.18 GB/s compact printing (see Section 6.4: Reuse Mode Throughput), with zero heap allocation inside the library during the loop.
Note: PRINT_BUF_LEN is your own initial print buffer size (e.g. #define PRINT_BUF_LEN 4096). When the buffer is too small, LJSON grows it automatically and updates ptr.p, so you don’t need to worry about overflow.
The three mechanisms behind this pattern are analyzed at source level in Section 7.10: Memory Pool, Section 7.11: Zero Copy, and Section 7.19: Print Buffer.
4.3 Minimal Example: Parse → Read → Print
#include <stdio.h>
#include "json.h"
int main(void)
{
/* Note: the parse API uses this buffer in place, so it must be a writable
char[] — never a string literal */
char text[] = "{\"Name\":\"LJSON\",\"Year\":2019,\"Score\":9.9,"
"\"Tags\":[\"fast\",\"stream\",\"json5\"]}";
size_t len = 0;
char *out = NULL;
/* 1. Parse: mode 1, classic DOM */
json_object *root = json_parse_str(text, sizeof(text) - 1);
if (!root) {
printf("parse failed!\n");
return -1;
}
/* 2. Read: get object members by key */
json_object *name = json_get_object_item(root, "Name", NULL);
json_object *year = json_get_object_item(root, "Year", NULL);
json_object *score = json_get_object_item(root, "Score", NULL);
printf("Name = %s\n", name->value.vstr);
printf("Year = %d\n", json_get_int_value(year));
printf("Score = %g\n", json_get_double_value(score));
/* 3. Read an array: get elements by index */
json_object *tags = json_get_object_item(root, "Tags", NULL);
int i, n = json_get_array_size(tags);
printf("Tags = [");
for (i = 0; i < n; ++i) {
json_object *item = json_get_array_item(tags, i, NULL);
printf("%s\"%s\"", i ? ", " : "", item->value.vstr);
}
printf("]\n");
/* 4. Print: DOM -> formatted string */
out = json_print_format(root, json_item_total_get(root), &len, NULL);
printf("format (%zu bytes):\n%s\n", len, out);
json_memory_free(out);
/* 5. Print: DOM -> compact string */
out = json_print_unformat(root, json_item_total_get(root), &len, NULL);
printf("unformat (%zu bytes):\n%s\n", len, out);
json_memory_free(out);
/* 6. Free the whole tree */
json_del_object(root);
return 0;
}
4.4 Memory-Pool Mode and Reuse Mode
Just replace json_parse_str with json_fast_parse_str (mode 2) or json_reuse_parse_str (mode 3); the only difference is one extra json_mem_t:
#include <stdio.h>
#include "json.h"
int main(void)
{
char data[] = "{\"Name\":\"LJSON\",\"Year\":2019,\"Score\":9.9,"
"\"Tags\":[\"fast\",\"stream\",\"json5\"]}";
size_t size = strlen(data);
json_object *json = NULL;
json_mem_t mem;
/* Assume data/size already holds a piece of JSON text (must be writable) */
pjson_memory_init(&mem); /* initialization, done only once */
/* Mode 2: memory-pool mode — strings are copied, original buffer untouched */
json = json_fast_parse_str(data, size, &mem);
/* Mode 3: reuse mode — strings reuse the original buffer in place (modified!),
and remain editable */
/* mem.valid = true; mark that memory is already available */
/* mem.obj_mgr.mem_size = size; let one block hold all objects */
/* json = json_reuse_parse_str(data, size, &mem); */
if (!json) {
printf("parse failed!\n");
pjson_memory_free(&mem);
return -1;
}
/* Count allocated objects from the pool; can be used as item_total when
printing, saving one recursive count */
int item_total = pjson_memory_statistics(&mem.obj_mgr) / (int)sizeof(json_object);
size_t len = 0;
char *out = json_print_format(json, item_total, &len, NULL);
printf("%s\n", out);
json_memory_free(out);
/* In memory-pool mode you cannot json_del_object per node,
only free everything at once */
pjson_memory_free(&mem);
return 0;
}
⚠️ In memory-pool / reuse mode, do not call json_del_object on individual nodes; only pjson_memory_free(&mem) frees everything at once.
In reuse mode the original buffer is modified in place and cannot be freed while the json is in use.
4.5 Two Ways to Speed Up Message Parsing
When handling “request/response message” style JSON — fixed structure, fixed field order — LJSON offers two acceleration techniques. They come from real production projects and can be copied directly.
4.5.1 Basics: Make Key Strings Constant
Start with a small optimization: define all keys as static json_string_t with lengths hard-coded at compile time, avoiding a strlen on every lookup.
/* Use a macro to hard-code the key name and length at once */
#define DEF_LJSON_STR(name, size) json_string_t JmixerMsgStr::name = \
{.str = const_cast<char *>(#name), .info = { .escaped = 0, .len = size }}
DEF_LJSON_STR(id, 2);
DEF_LJSON_STR(cid, 3);
DEF_LJSON_STR(pack_ms, 7);
DEF_LJSON_STR(samp_rate, 9);
/* When the value differs from the name, use the value-taking version */
#define DEF_LJSON_STR_VAL(name, val, size) json_string_t JmixerMsgStr::name = \
{.str = const_cast<char *>(val), .info = { .escaped = 0, .len = size }}
DEF_LJSON_STR_VAL(g711a, "G.711A", 6);
After that, every lookup uses e.g. JmixerMsgStr::pack_ms.str — no string literals, no strlen.
4.5.2 Speed-Up Mode 1: Get items First, Then Access in Bulk
Applies when: the payload contains a JSON_ARRAY, or a JSON_OBJECT with many members, and you need to iterate or repeatedly look up by key.
json_get_items extracts all children under a JSON_ARRAY / JSON_OBJECT into one contiguous array items:
- Array (
JSON_ARRAY): O(1) access by index, faster than json_get_array_item’s O(N)
- Object (
JSON_OBJECT): O(logN) binary search by key hash (it qsorts internally and flags hash collisions)
A real case — parsing a “mixer list” (arrays, and objects nested inside arrays):
int JmixerMsgMixer::parse(json_object *json, json_items_t *items)
{
json_object *item = NULL, *sub = NULL;
/* ① Ordinary fields: just use json_get_object_item as usual */
item = json_get_object_item(json, JmixerMsgStr::cid.str, NULL);
if (!item)
return -1;
cid = static_cast<uint32_t>(json_get_lint_value(item));
if (cid == 0)
return -1;
/* ② Facing an array: get_items first, then iterate by index in O(1) */
item = json_get_object_item(json, JmixerMsgStr::ids.str, NULL);
if (!item)
return -1;
if (json_get_items(item, items) < 0)
return -1;
for (size_t i = 0; i < items->count; ++i) {
ids.push_back(static_cast<uint32_t>(json_get_lint_value(items->items[i].json)));
}
if (ids.empty())
return -1;
/* ③ Objects nested in the array: fetch by key from items->items[i].json */
item = json_get_object_item(json, JmixerMsgStr::set_ids.str, NULL);
if (item) {
set_flag = true;
} else {
item = json_get_object_item(json, JmixerMsgStr::add_ids.str, NULL);
set_flag = false;
}
if (item) {
if (json_get_items(item, items) == 0) {
for (size_t i = 0; i < items->count; ++i) {
AudioMixerSource v;
sub = json_get_object_item(items->items[i].json, JmixerMsgStr::id.str, NULL);
if (!sub)
continue;
v.id = static_cast<uint32_t>(json_get_lint_value(sub));
sub = json_get_object_item(items->items[i].json, JmixerMsgStr::decay.str, NULL);
if (!sub)
continue;
v.decay = static_cast<uint8_t>(json_get_int_value(sub));
if (v.decay > 9)
v.decay = 9;
new_ids.push_back(v);
}
}
}
return 0;
}
Three key points
items is provided and reused by the caller (usually defined outside the loop, or passed per level as a json_items_t items[2] array); as long as capacity suffices, nothing is allocated — which is exactly why it can be used in the zero-heap-allocation mode.
- Each nesting level needs its own
json_items_t. The example above reuses a single items because only one level is live at a time; if two levels must be held simultaneously (e.g. the idxs and crops arrays in JVmixerMsgLinkParam), pass items[2].
- Call
memset(&items, 0, sizeof(items)) before use, and json_free_items(&items) after everything (if items is an array of json_items_t, call it separately for each element).
Binary search by key in the object case:
json_string_t jkey = {0};
jkey.str = (char *)"Name";
json_string_info_update(&jkey); /* auto-fill info.len / info.escaped */
uint32_t hash = json_string_hash_code(&jkey);
json_object *found = json_search_object_item(&items, &jkey, hash);
4.5.3 Speed-Up Mode 2: Pre-fill prev, Continue the Search
Applies when: fields appear in a fixed order and you only need to read them once in order. The third parameter prev of json_get_object_item is “the node found last time”; passing it makes the search continue after prev instead of restarting from the head every time.
A real case — parsing “area parameters” (fixed order x → y → w → h):
int JVmixerMsgArea::parse(json_object *json)
{
json_object *item = NULL, *prev = NULL;
item = json_get_object_item(json, JVmixerMsgStr::x.str, &prev);
if (!item)
return -1;
x = static_cast<uint16_t>(json_get_int_value(item));
prev = item; /* ★ use this result as the starting point for the next search */
item = json_get_object_item(json, JVmixerMsgStr::y.str, &prev);
if (!item)
return -1;
y = static_cast<uint16_t>(json_get_int_value(item));
prev = item;
item = json_get_object_item(json, JVmixerMsgStr::w.str, &prev);
if (!item)
return -1;
w = static_cast<uint16_t>(json_get_int_value(item));
prev = item;
item = json_get_object_item(json, JVmixerMsgStr::h.str, &prev);
if (!item)
return -1;
h = static_cast<uint16_t>(json_get_int_value(item));
return 0;
}
Why is this faster?
Without prev: restart from the list head each time → O(N) + O(N) + O(N) + O(N) = O(4N)
With prev: continue from the previous position → only 1~2 steps on average ≈ O(N)
For objects with dozens of fields this is a several-fold difference, and the more fields, the bigger the gain.
⚠️ Precondition: fields must appear in the JSON in the same order as in your code.
If some key appears before prev, json_get_object_item wraps back to the list head and searches a full circle (nothing is missed, but no speed-up either).
So when field order is not guaranteed, use json_get_items + binary search from Section 4.5.2 instead.
4.5.4 How to Choose Between the Two Modes
| Scenario |
Recommendation |
Reason |
| Iterate all elements of an array |
Mode 1 (items) |
O(1) by index, and a contiguous array is cache friendly |
| Many fields, fixed order, read once |
Mode 2 (prev) |
Continues the search; barely walks the list |
| Many fields, unpredictable order, repeated key lookups |
Mode 1 (items + binary search) |
O(logN), independent of order |
| Objects nested in arrays, fetched by key one by one |
Combine both |
items gets the element, then fetch by key |
| Parsed once outside a loop, very few fields |
Just json_get_object_item(json, key, NULL) |
No need to optimize |
The two can be stacked: use items for arrays first, then use prev with fixed order inside each element.
4.6 Editing: Add / Modify / Delete
#include <stdio.h>
#include <string.h>
#include "json.h"
/* It is recommended to follow `4.5.1 Basics: Make Key Strings Constant` and make
keys constant instead of recomputing them with set_str every time */
static void set_str(json_string_t *js, char *s)
{
js->info.len = 0; /* len must be cleared first, otherwise update won't compute it */
js->str = s;
json_string_info_update(js); /* fill the len and escaped flags */
}
int main(void)
{
json_object *root = json_create_object();
/* Add values of various types */
json_string_t jkey;
set_str(&jkey, (char *)"Name");
json_string_t jval;
set_str(&jval, (char *)"LJSON");
json_add_string_to_object(root, &jkey, &jval);
set_str(&jkey, (char *)"Age");
json_add_int_to_object(root, &jkey, 30);
set_str(&jkey, (char *)"Score");
json_add_double_to_object(root, &jkey, 9.9);
set_str(&jkey, (char *)"Big");
json_add_lint_to_object(root, &jkey, 1234567890123LL);
set_str(&jkey, (char *)"Mask");
json_add_hex_to_object(root, &jkey, 0xDEADBEEF);
/* Add an array */
set_str(&jkey, (char *)"Hobby");
json_object *hobby = json_add_array_to_object(root, &jkey);
json_string_t h1, h2;
set_str(&h1, (char *)"Reading");
set_str(&h2, (char *)"Walking");
json_add_string_to_array(hobby, &h1);
json_add_string_to_array(hobby, &h2);
/* Modify */
json_object *age = json_get_object_item(root, "Age", NULL);
json_set_int_value(age, 31);
/* Delete (by key / by index) */
json_del_item_from_object(root, "Score");
json_del_item_from_array(hobby, 0);
/* Replace */
json_object *newage = json_create_int(32);
set_str(&jkey, (char *)"NewAge"); /* empty-key support is off by default, so set it before replacing */
json_set_key(newage, &jkey);
json_replace_item_in_object(root, newage);
/* Deep copy */
json_object *copy = json_deepcopy(root);
/* C11 generic style (or C++ overload style): one line, no type suffix to remember */
set_str(&jkey, (char *)"Generic");
json_object_append(root, &jkey, 3.14159); /* automatically recognized as double */
size_t len = 0;
char *out = json_print_format(root, json_item_total_get(root), &len, NULL);
printf("%s\n", out);
json_memory_free(out);
json_del_object(copy);
json_del_object(root);
return 0;
}
4.7 SAX Parsing: Callback Driven
SAX parsing does not build a DOM tree; it calls you back once per parsed value. It suits “extract fields from a huge file” or “JSON to JSON”.
For the callback function, refer to _sax_parser_cb in json_test.c.
4.8 SAX Printing: Output Directly Without a DOM
This is the recommended default printing approach. When your data already lives in your own structures, do not build a DOM first.
You can also refer to test_json_sax_print in json_test.c.
#include <stdio.h>
#include "json.h"
/* It is recommended to follow `4.5.1 Basics: Make Key Strings Constant` and make
keys constant instead of recomputing them with set_str every time */
static void set_str(json_string_t *js, char *s)
{
js->info.len = 0; /* len must be cleared first, otherwise update won't compute it */
js->str = s;
json_string_info_update(js); /* fill the len and escaped flags */
}
int main(void)
{
json_sax_print_hd hd = NULL;
json_string_t jkey, jstr;
size_t len = 0;
char *out = NULL;
/* Start: formatted output to a string (the 2nd arg is the estimated total
object count, used to allocate enough buffer in one shot) */
hd = json_sax_print_format_start(100, NULL);
/* Top-level left brace */
json_sax_print_object_start(hd, NULL);
set_str(&jkey, (char *)"Name");
set_str(&jstr, (char *)"LengJing");
json_sax_print_object_item(hd, &jkey, &jstr);
set_str(&jkey, (char *)"Age");
json_sax_print_object_item(hd, &jkey, 30); /* C11 generic: auto-detected as int32 */
set_str(&jkey, (char *)"Phone");
set_str(&jstr, (char *)"18368887550");
json_sax_print_object_item(hd, &jkey, &jstr);
/* Nested array */
set_str(&jkey, (char *)"Hobby");
json_sax_print_array_start(hd, &jkey);
set_str(&jstr, (char *)"Reading");
json_sax_print_array_item(hd, &jstr);
set_str(&jstr, (char *)"Walking");
json_sax_print_array_item(hd, &jstr);
set_str(&jstr, (char *)"Thinking");
json_sax_print_array_item(hd, &jstr);
json_sax_print_array_finish(hd);
/* Top-level right brace */
json_sax_print_object_finish(hd);
/* Finish: get the resulting string */
out = json_sax_print_finish(hd, &len, NULL);
printf("%s\n", out);
json_memory_free(out);
return 0;
}
Printing to a file (true streaming) only requires swapping start for json_sax_fprint_format_start:
/* Generate while writing to the file; no need to accumulate the whole string in memory */
hd = json_sax_fprint_format_start(100, "out.json", NULL);
/* ... the same series of json_sax_print_xxx ... */
json_sax_print_finish(hd, NULL, NULL);
4.9 Streaming File Parsing and Printing
#include "json.h"
int main(void)
{
json_object *json = NULL;
json_mem_t mem;
/* Mode 5: DOM file stream + memory pool: parse while reading + pool allocation */
pjson_memory_init(&mem);
json = json_fast_parse_file("big.json", &mem);
/* Printing to a file stream (other than mode 2): print while writing */
int item_total = pjson_memory_statistics(&mem.obj_mgr) / (int)sizeof(json_object);
json_fprint_format(json, item_total, "out.format.json", NULL);
pjson_memory_free(&mem);
return 0;
}
The value of true streaming: 1.7 GB of citm_catalog.json completes “read + parse + format + write” in mode 7 in just 2946 ms, with constant peak memory.
4.10 Using the Numeric Engine Standalone
jnum.h can be used on its own without json.h — it is an independent number conversion library:
#include <stdio.h>
#include "jnum.h"
int main(void)
{
char buf[32]; /* the docs recommend at least 27 bytes */
int len;
/* Number -> string */
len = jnum_dtoa(3.14159265358979, buf); printf("dtoa : %s (%d)\n", buf, len);
len = jnum_itoa(-123456, buf); printf("itoa : %s (%d)\n", buf, len);
len = jnum_ltoa(1234567890123LL, buf); printf("ltoa : %s (%d)\n", buf, len);
len = jnum_htoa(0xDEADBEEF, buf); printf("htoa : %s (%d)\n", buf, len);
len = jnum_lhtoa(0x123456789ABCDEFULL, buf); printf("lhtoa: %s (%d)\n", buf, len);
/* String -> number (jnum_atod is 2~19x faster than strtod in the v5.0.6 benchmark) */
printf("atod : %g\n", jnum_atod("3.14159265358979"));
printf("atoi : %d\n", jnum_atoi("-123456"));
printf("atol : %lld\n", (long long)jnum_atol("1234567890123"));
printf("atoh : %u\n", jnum_atoh("0xDEADBEEF"));
/* When you need to know the parsed type, use jnum_parse */
jnum_type_t type;
jnum_value_t value;
int used = jnum_parse(" 0x1F", &type, &value); /* skips leading blanks automatically */
printf("type=%d, hex=0x%X, used=%d\n", type, value.vhex, used);
return 0;
}
4.11 The Binary Extension Type
LJSON supports a binary data extension whose text format is <len:data> (for example <8:\x01\x02...>):
#include <string.h>
#include "json.h"
#include <stdio.h>
#include "json.h"
int main(void)
{
unsigned int raw[8] = {1, 2, 3, 4, 5, 6, 7, 8};
/* Construct */
json_binary_t jbin;
jbin.bin = raw;
jbin.info.len = sizeof(raw);
json_object *bin = json_create_binary(&jbin);
/* Read */
json_binary_t out;
json_get_binary_value(bin, &out);
printf("len = %u\n", out.info.len);
/* As an object member it prints in the <8:...> form */
json_object *root = json_create_object();
json_string_t jkey;
jkey.str = (char *)"Binary";
json_string_info_update(&jkey);
json_add_binary_to_object(root, &jkey, &jbin);
size_t len = 0;
char *s = json_print_unformat(root, json_item_total_get(root), &len, NULL);
printf("%s len=%d\n", s, (int)len);
json_memory_free(s);
json_del_object(root);
return 0;
}
5. Building and Running
5.1 How to Build and Install
① Build directly (simplest — two .c files are enough)
gcc -o ljson json.c jnum.c json_test.c -O2 -ffunction-sections -fdata-sections -W -Wall
If you only want the numeric engine:
gcc -o jnum_test jnum.c jnum_test.c -O2 -W -Wall
② Build + install with IMAKE
make O=<build output dir> && make O=<build output dir> DESTDIR=<install dir> install
The install target installs the build artifacts (the library plus the json.h / jnum.h headers) into the directory given by DESTDIR,
so other projects can simply #include <json.h> and link against it.
③ Cross-compile + install
make O=<build output dir> CROSS_COMPILE=<cross compiler prefix> && make O=<build output dir> DESTDIR=<install dir> install
For example, cross-compiling for ARM:
make O=obj-arm CROSS_COMPILE=arm-linux-gnueabihf- && make O=obj-arm DESTDIR=./install-arm install
④ Windows (MSVC)
Open MSC\ljson\ljson.sln with Visual Studio 2022 and build.
Note: under MSVC, JSON_MANUAL_LOOP_UNFOLD and JNUM_MANUAL_LOOP_UNFOLD default to 0 (manual unrolling is actually slower on MSVC),
and functions such as jnum_atoi in jnum.h are not inline under MSVC either (MSVC gets slower with inline). All of this is handled automatically inside the library.
5.2 Compile-Time Switches
① Choose the float→string algorithm
gcc -DJSON_DTOA_ALGORITHM=n ... # or make DTOA=n
| n |
Algorithm |
Description |
| 0 |
ldouble (in-house, default) |
Fastest, 17-digit precision, always the shortest exact representation |
| 1 |
C standard library sprintf (%1.16g) |
Slowest, but fully standard behavior |
| 2 |
personally optimized grisu2 |
Google’s classic algorithm |
| 3 |
personally optimized dragonbox |
A newer algorithm, faster than grisu2 |
② Choose large or small lookup tables
gcc -DUSING_SMALL_LUT=n ... # or make SMALL=n
| n |
Description |
| 0 |
Large lookup table (default), may be slightly faster |
| 1 |
Small lookup table, about 5 KB smaller code segment |
Small lookup tables suit embedded scenarios where instruction cache is tight or firmware size is sensitive.
5.3 How to Run
./ljson <json file name> <test index 1-7> # test various parse modes and print modes
./ljson <json file name> <test index 1-3> diswr # test various parse/print modes without generating files
./ljson <json file name> <repeat count greater than 7> # mode 3 (reuse mode): repeat parse N times
./ljson <json file name> <repeat count greater than 7> print # reuse print mode: repeat DOM->string printing N times
Mapping:
| Argument |
API called |
Mode |
1 |
json_parse_str() |
DOM classic mode |
2 |
json_fast_parse_str() |
DOM memory-pool mode |
3 |
json_reuse_parse_str() |
DOM reuse mode |
4 |
json_parse_file() |
DOM file-stream mode |
5 |
json_fast_parse_file() |
DOM file-stream + memory pool |
6 |
json_sax_parse_str() |
SAX mode |
7 |
json_sax_parse_file() |
SAX file-stream mode |
>7 |
mode 3 + pjson_memory_refresh() loop |
reuse mode, repeated parsing |
>7 print |
json_print_format/unformat() loop |
reuse mode, repeated printing |
5.4 Debugging
Set JSON_ERROR_PRINT_ENABLE to 1 in json.c and rebuild; when parsing/printing fails, the library prints the failing function name, line number, and nearby text, making it easy to locate invalid JSON.
You can also specify it at compile time:
gcc -DJSON_ERROR_PRINT_ENABLE=1 -o ljson json.c jnum.c json_test.c -O2 -W -Wall
5.5 Parse Configuration
The following macros live in json.c; the table lists their default values in the source:
| Macro |
Default |
Description |
JSON5 |
JSON_PARSE_SKIP_COMMENT |
0 |
Allow C-style single-line/multi-line comments |
✅ |
JSON_PARSE_LAST_COMMA |
1 |
Allow a trailing comma after the last array/object element |
✅ |
JSON_PARSE_EMPTY_KEY |
0 |
Allow empty-string keys |
❌ |
JSON_PARSE_SPECIAL_CHAR |
1 |
Allow special characters (e.g. newlines) inside strings |
✅ |
JSON_PARSE_SPECIAL_QUOTES |
0 |
Allow single-quoted strings/keys and unquoted keys |
✅ |
JSON_PARSE_HEX_NUM |
1 |
Allow hex numbers (e.g. 0xFF) |
✅ |
JSON_PARSE_SPECIAL_NUM |
1 |
Allow special numbers: +99 .1234 10. 001 etc. |
✅ |
JSON_PARSE_SPECIAL_DOUBLE |
1 |
Allow NaN Infinity -Infinity |
✅ |
JSON_PARSE_SINGLE_VALUE |
1 |
Allow a JSON value that does not start with array/object |
❌ |
JSON_PARSE_FINISHED_CHAR |
0 |
Ignore trailing-character checks after parsing completes |
❌ |
JSON_ERROR_PRINT_ENABLE |
0 |
Whether to print error information |
— |
Related behavior switches (also in json.c):
| Macro |
Default |
Description |
JSON_DTOA_ALGORITHM |
0 |
float→string algorithm (see 5.2) |
JSON_MANUAL_LOOP_UNFOLD |
1 (0 on MSVC) |
Whether to manually unroll parse/print loops |
JSON_PRINT_UTF16_SUPPORT |
0 |
Whether to convert control characters to \u00XX when printing |
USING_SMALL_LUT |
0 |
Whether the numeric engine uses small lookup tables |
On the JSON5 default policy (important)
LJSON fully supports JSON5, but the default configuration is speed first:
- The two JSON5 features that sit on the parse hot path and cost the most — comments (
JSON_PARSE_SKIP_COMMENT) and single-quoted/unquoted keys (JSON_PARSE_SPECIAL_QUOTES) — default to 0 (off), because they add one extra check per character fetched.
- The remaining JSON5 features with little impact on the hot path (trailing commas, special characters, hex, special numbers,
NaN/Infinity) default to 1 (on).
When you need full JSON5 / lenient parsing, set the corresponding macro to 1 and rebuild. Enabling comments and special quotes measurably slows parsing — this is a deliberate trade-off.
On standards compliance
If you need 100% compliance with the strict validation of nativejson-benchmark, set JSON_PARSE_EMPTY_KEY to 1 and all other values to 0.
6.1 Test Notes and Environment
Test samples
The samples come from the nativejson-benchmark project. To stress large-file scenarios, they were amplified by repeated concatenation:
| Sample |
Original size |
Amplified |
Data characteristics |
twitter.json |
631,514 B |
×1000 = 603 MB |
string + integer heavy, medium nesting |
citm_catalog.json |
1,727,204 B |
×1000 = 1.7 GB |
deeply nested objects |
canada.json |
2,251,051 B |
×100 = 215 MB |
float-heavy (geographic coordinates) |
Test script
#!/bin/bash
src=$1
if [ -z $src ] || [ ! -e $src ]; then
echo "Usage: $0 <json file>"
exit 1
fi
run_cmd() {
printf "%-15s " $1
eval $@
sync
sleep 0.1
}
for i in `seq 1 7`; do
run_cmd ./ljson $src $i diswr
done
run_cmd ./cjson $src
run_cmd ./rapidjson $src
run_cmd ./yyjson $src
run_cmd ./yyjson $src 1
run_cmd ./strdup $src
How the comparison libraries were built (-O2, default options):
gcc -o cjson cjson_test.c cJSON.c -O2 # cJSON
g++ -o rapidjson rapidjson_test.c -Iinclude -O2 # RapidJSON
gcc -o yyjson yyjson_test.c src/yyjson.c -Isrc -O2 # yyjson
gcc -o strdup strdup_test.c -O2 # strdup and strlen
Timing conventions (read this before reading the numbers)
| Mode |
Output item |
Meaning |
| DOM 1 / 2 / 3 |
read and parse separately |
parse excludes file reading time |
| DOM 1 / 2 / 3 |
format / unformat |
time to print into a string, excludes file writing |
| DOM 4 / 5 |
read+parse |
parsing while reading, cannot be split, includes reading |
| DOM 4 / 5 |
format+write / unformat+write |
printing while writing, includes file writing |
| SAX 6 |
parse+format |
parse and format on the same pipeline |
| SAX 7 |
read+parse+format+write |
whole flow on one pipeline, includes reading and writing |
strdup |
strdup / strlen |
memory bandwidth baseline: how long it takes to copy / scan the whole file |
The two yyjson modes used as controls
unm (unmutable): read-only mode; the parsed structure cannot be modified
mut (mutable): editable mode; the parsed structure can be modified
6.2 Intel i7-1260P (v5.0.5, latest) ★
Test platform: PC | CPU: Intel i7-1260P | OS: Debian 13 (VMWare) | LJSON v5.0.5
Results: LJSON is up to 562% faster than cJSON at parsing and up to 2283% faster at printing; up to 172% faster than RapidJSON at parsing and up to 285% faster at printing; up to 145% faster than yyjson (mutable mode) at parsing and up to 168% faster at printing (times exclude file reading/writing)

This is the baseline data for this README; the terminal outputs in Sections 6.3 and 6.4 come from the same test run.
Cross-validating the figure against the measurements, item by item
The six “up to” percentages in the figure can all be reproduced exactly from the terminal output in Section 6.3 (identical after rounding). This proves the figure and the terminal output come from the same source, so both can be cited with confidence:
| Conclusion in the figure |
Sample and metric that reproduces it |
Best LJSON value |
Comparison library |
Calculation |
Result |
| vs cJSON parse 562% |
canada · parse |
281 (mode 3) |
1862 |
(1862−281)/281 |
562.6% ✓ |
| vs cJSON print 2283% |
canada · unformat </len:data></uint16_t></uint16_t></uint16_t></uint16_t></uint8_t></uint32_t></uint32_t></uint32_t></len:data></len:data> |
|
|
|
|
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论