Complete Guide for
in C and C++
Seven libraries, one official test suite, and the bugs the READMEs leave out.
Neither language ships a JSON5 parser. We built seven community libraries with GCC 15.2, ran each against the official json5-tests corpus of 114 documents, then probed edge cases, nesting depth, error messages and parse speed on one machine.
Two libraries passed all 114 cases: yyjson in C and Json5Cpp by mqnc in C++. The rest stumble on hex numbers, the spelling of Infinity, escaped surrogate pairs or a stack overflow. Every code sample below was compiled and run, and the output shown is real.
TL;DR: For reading JSON5 from C or C++, use yyjson (MIT, one .c and one .h, 114 of 114 official cases, about 1.3 ms for an 888 KB file). For C++ types and a JSON5 writer, mqnc/json5cpp also passes all 114 cases but is very slow on large files. Treat the others as unfinished: they accept or reject documents the specification says otherwise.
Choosing a Library
The standard libraries of both languages have no JSON support at all, and the best-known C++ JSON libraries offer only partial relaxations (see the note below the table). What exists for JSON5 is a handful of small, independent projects with very different levels of care. The table lists the seven we tested, ordered by score. The score is the number of the 114 documents in the official corpus that the library handled as the file extension demands: .json and .json5 must parse, .js and .txt must fail. The conformance page explains the corpus and its extension convention.
| Library | Language | License | Version tested | Score (of 114) | Writes JSON5 | Main caveat |
|---|---|---|---|---|---|---|
| yyjson | C | MIT | 0.13.0, 2026-09-08 | 114 | JSON only | 0.13.0 rejects a raw tab inside a string |
| mqnc/json5cpp | C++17 | MIT | commit eb26b26, 2025-06-16; no release | 114 | Parse time grows with the square of the input; an escaped surrogate pair becomes an empty string | |
| YAJL, json5 branch | C | ISC | commit e9672c3, 2020-08-04 | 109 | Never merged upstream; accepts an unterminated comment; rejects non-ASCII keys | |
| json5pp | C++11 | MIT | commit 559202e, 2020-11-16 (tag v2.2.0) | 106 | Reads infinity, not Infinity | |
| mortie/json5cpp | C++11 on JsonCpp | MIT | commit 592f623, 2025-09-12 (tag v1.1.1) | 105 | Accepts octal-looking numbers and a lone decimal point | |
| json.h | C and C++ | Unlicense | commit 6da34a6, 2026-11-09 | 103 | No \x escapes; backslash-newline continuation fails | |
| P-i-N/json5 | C++17 or later | MIT | commit 11084bf, 2021-05-03; no release | 45 as is, about 79 with the root wrapped in [ ] | Every hex number reads as 0; the root must be an array or object |
How we tested. Ubuntu 26.04 under WSL2 on an Intel Core i9-9900, GCC 15.2.0 at -O2, on November 29, 2026. The corpus is json5-tests commit ceb24d4, the same revision used on the conformance page. Each library read one file per process; an exit code other than pass or fail would have counted as a crash, and none of the seven crashed on the corpus. We did not run libpdjson5, cj5 or judo, so the table makes no claim about them. For reference, GitHub lists libpdjson5 as Unlicense, cj5 as MIT and judo as GPL-3.0.
Relaxed is not JSON5. RapidJSON offers kParseCommentsFlag, kParseTrailingCommasFlag and kParseNanAndInfFlag; Boost.JSON offers allow_comments, allow_trailing_commas and allow_infinity_and_nan; nlohmann/json 3.12.0 can ignore comments, and its development branch adds ignore_trailing_commas. These cover part of the format. We did not test whether they read single-quoted strings, unquoted keys or hex numbers, so do not call them JSON5 parsers. If you already link SQLite 3.42.0 or newer, json() converts JSON5 text to canonical JSON; we ran select json('{ name: ''edge-proxy'', port: 0x1F90, timeout: .75, tags: [''a'',], /* c */ }') on SQLite 3.46.1 and got {"name":"edge-proxy","port":8080,"timeout":0.75,"tags":["a"]}.
yyjson: the C Library to Start With
yyjson reads JSON5 when you pass YYJSON_READ_JSON5, a flag added in 0.12.0. It is a bundle of eight smaller flags (nine on the development branch): trailing commas, comments, Infinity and NaN, extended numbers (hex, leading or trailing decimal point, a plus sign), extended escapes, extended whitespace, single-quoted strings and unquoted keys. The parser builds an immutable document that owns every string, and one call frees it. This program reads the file below into a struct and prints it.
// server.json5 - edge proxy settings
{
name: 'edge-proxy',
port: 0x1F90, // 8080
timeout: .75, // seconds
tls: { enabled: true, cert: "/etc/ssl/edge.pem", },
upstreams: [
{ host: "10.0.0.5", weight: 2 },
{ host: "10.0.0.6", weight: 1 }, // trailing comma is fine
],
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "yyjson.h"
typedef struct {
char name[64];
int port;
double timeout;
int tls_enabled;
size_t n_upstreams;
} Config;
/* Read a whole file into a NUL-terminated buffer. */
static char *slurp(const char *path, size_t *len) {
FILE *f = fopen(path, "rb");
if (!f) return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = malloc((size_t)n + 1);
if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) { fclose(f); free(buf); return NULL; }
buf[n] = '\0';
fclose(f);
*len = (size_t)n;
return buf;
}
int main(int argc, char **argv) {
const char *path = argc > 1 ? argv[1] : "server.json5";
size_t len = 0;
char *text = slurp(path, &len);
if (!text) { fprintf(stderr, "cannot read %s\n", path); return 2; }
yyjson_read_err err;
yyjson_doc *doc = yyjson_read_opts(text, len, YYJSON_READ_JSON5, NULL, &err);
if (!doc) {
size_t line = 0, col = 0, chr = 0;
yyjson_locate_pos(text, len, err.pos, &line, &col, &chr);
fprintf(stderr, "%s:%zu:%zu: %s\n", path, line, col, err.msg);
free(text);
return 1;
}
yyjson_val *root = yyjson_doc_get_root(doc);
Config cfg = {0};
const char *name = yyjson_get_str(yyjson_obj_get(root, "name"));
snprintf(cfg.name, sizeof cfg.name, "%s", name ? name : "");
cfg.port = (int)yyjson_get_sint(yyjson_obj_get(root, "port"));
cfg.timeout = yyjson_get_real(yyjson_obj_get(root, "timeout"));
cfg.tls_enabled = yyjson_get_bool(yyjson_obj_get(yyjson_obj_get(root, "tls"), "enabled"));
yyjson_val *ups = yyjson_obj_get(root, "upstreams");
cfg.n_upstreams = yyjson_arr_size(ups);
printf("name=%s port=%d timeout=%.2f tls=%d upstreams=%zu\n",
cfg.name, cfg.port, cfg.timeout, cfg.tls_enabled, cfg.n_upstreams);
size_t idx, max;
yyjson_val *u;
yyjson_arr_foreach(ups, idx, max, u) {
printf(" %s weight %d\n",
yyjson_get_str(yyjson_obj_get(u, "host")),
(int)yyjson_get_sint(yyjson_obj_get(u, "weight")));
}
yyjson_doc_free(doc);
free(text);
return 0;
}Output for that file, and for a copy with the comma after port: 8080 removed:
name=edge-proxy port=8080 timeout=0.75 tls=1 upstreams=2
10.0.0.5 weight 2
10.0.0.6 weight 1
broken.json5:4:3: unexpected character, expected ',' or '}'Where yyjson differs from the specification, in version 0.13.0:
- Raw tabs in strings fail. The release rejects a literal tab inside a quoted string, which ECMAScript 5 and therefore JSON5 allow. The fix, a new
YYJSON_READ_ALLOW_UNESCAPED_CTRLbit inside the JSON5 flag, was committed on November 19, 2026, after the 0.13.0 tag, so a release build needs\tescapes until the next version. - Extra escapes mean something else. The documentation lists
\aand\eas extensions. We confirmed that'\a'decodes to U+0007, where the specification says a backslash before an ordinary letter yields the letter (the reference JavaScript package, version 2.2.3, returns"a"). - Hex stops at 64 bits.
0x7FFFFFFFFFFFFFFFFreturns "hex number overflow", while the specification sets no limit on hex digits. - Lone surrogates fail.
"\ud83d"is an error ("no low surrogate"), and invalid UTF-8 is rejected unless you addYYJSON_READ_ALLOW_INVALID_UNICODE. - Nesting is unlimited by default.
YYJSON_READER_DEPTH_LIMITis a compile-time macro whose default of 0 means no limit.
It also accepts extras the specification leaves out, such as infinity in any letter case. That is allowed, because a parser may accept more than the grammar, but it means yyjson cannot act as a validator for strict JSON5.
The YAJL json5 Branch and Its Status
YAJL is the C stream parser that many projects embed. Its original repository, lloyd/yajl, has had no commit on its default branch since September 24, 2015; its newest tag is 2.1.0, and issue 252 asks "Projet dead ?" (July 2023). The JSON5 work lives in pull request 211, opened on September 1, 2018 from the json5 branch of anjohnson/yajl. It was never merged, and its last commit is dated August 4, 2020. EPICS Base carries its own copy of YAJL and merged JSON5 support into it for release 7.0 on January 5, 2021.
On the branch, yajl_tree_parse() always accepts JSON5; the streaming parser needs yajl_config(h, yajl_allow_json5, 1); and the generator gains yajl_gen_json5. It scored 109 of 114: it fails the two documents whose lines end with a lone carriage return, both non-ASCII key documents, and it accepts a document ending in an unterminated block comment. It also rejected a raw tab in a string, U+00A0 and a byte order mark between tokens, and +NaN or -NaN, all of which are legal. We compiled the library sources directly, without CMake, and ran this:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>
int main(void) {
const char *text = "{ name: 'edge-proxy', port: 0x1F90, timeout: .75, tags: ['blue', 'green',], }";
char errbuf[256];
yajl_val root = yajl_tree_parse(text, errbuf, sizeof errbuf);
if (!root) { fprintf(stderr, "parse failed: %s\n", errbuf); return 1; }
const char *name_path[] = { "name", NULL };
const char *port_path[] = { "port", NULL };
yajl_val name = yajl_tree_get(root, name_path, yajl_t_string);
yajl_val port = yajl_tree_get(root, port_path, yajl_t_number);
printf("name=%s port=%lld\n", YAJL_GET_STRING(name), YAJL_GET_INTEGER(port));
yajl_tree_free(root);
/* Generator: the json5 option allows NaN, Infinity and unquoted keys. */
yajl_gen g = yajl_gen_alloc(NULL);
yajl_gen_config(g, yajl_gen_json5, 1);
yajl_gen_map_open(g);
yajl_gen_string(g, (const unsigned char *)"ceiling", 7);
yajl_gen_double(g, INFINITY);
yajl_gen_string(g, (const unsigned char *)"unset", 5);
yajl_gen_double(g, NAN);
yajl_gen_map_close(g);
const unsigned char *buf; size_t len;
yajl_gen_get_buf(g, &buf, &len);
printf("%.*s\n", (int)len, buf);
yajl_gen_free(g);
return 0;
}name=edge-proxy port=8080
{ceiling:+Infinity,unset:NaN} Adopting a branch that its author stopped touching in 2020 means owning it. It is a reasonable choice only if you already ship YAJL and need the generator's unquoted keys and +Infinity.
json.h: One Header for C and C++
json.h parses into one read-only allocation, so freeing the tree is a single free(). Calling json_parse_ex() with json_parse_flags_allow_json5 turns on nine individual flags: trailing commas, unquoted keys, C-style comments, single-quoted strings, hex numbers, a leading plus, leading or trailing decimal points, Infinity and NaN, and multi-line strings. Numbers stay as the original text, so you convert them yourself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json.h"
int main(int argc, char **argv) {
const char *text = argc > 1 ? argv[1]
: "{ name: 'edge-proxy', port: 0x1F90, timeout: .75, tls: { enabled: true, }, }";
struct json_parse_result_s res;
struct json_value_s *root = json_parse_ex(text, strlen(text),
json_parse_flags_allow_json5, NULL, NULL, &res);
if (!root) {
fprintf(stderr, "parse error %zu at byte %zu (line %zu, column %zu)\n",
res.error, res.error_offset, res.error_line_no, res.error_row_no);
return 1;
}
struct json_object_s *obj = json_value_as_object(root);
for (struct json_object_element_s *e = obj->start; e; e = e->next) {
struct json_number_s *n = json_value_as_number(e->value);
struct json_string_s *s = json_value_as_string(e->value);
if (n) printf("%s = number, text \"%s\"\n", e->name->string, n->number);
else if (s) printf("%s = string \"%s\"\n", e->name->string, s->string);
else printf("%s = type %zu\n", e->name->string, e->value->type);
}
free(root);
return 0;
}name = string "edge-proxy"
port = number, text "0x1F90"
timeout = number, text ".75"
tls = type 2 A malformed three-line document (a: 1 and b: 2 with no comma between them) produced parse error 1 at byte 11 (line 3, column 3). The score of 103 has two causes. First, "multi-line strings" in this library means a raw newline inside a string, which the specification forbids (the corpus file unescaped-multi-line-string.txt was accepted), while the real JSON5 feature, a backslash before a newline, was rejected. Second, escapes are limited to the strict JSON set: \x41, \a, \v and \0 all failed. It also rejected non-ASCII keys, a byte order mark, U+00A0 between tokens and a raw tab in a string, and accepted the key 1a. Reading Infinity works, but if you write the tree back with json_write_minified(), infinity is printed as 1.7976931348623158e308 and NaN as 0.
The C++ Libraries
Four C++ libraries read and write JSON5. They give you typed values and exceptions or error objects, which is nicer than C accessors, but each has a flaw you should know before adopting it. Samples for each were compiled with GCC 15.2.
mqnc/json5cpp
A port of the JavaScript reference parser, header-only, with a std::variant value type. It scored 114 of 114. Its README is candid: numbers are doubles only (exact up to 2^53), only UTF-8 is read, and it should not be used where security matters. Our probes add three more. The escape pair '\ud83d\ude00' parses to a zero-byte string, although the same emoji typed literally survives. 1e400 throws a bare std::out_of_range with the message "stod" instead of a syntax error, where the reference JavaScript package returns Infinity. And parsing is quadratic: documents of 21 KB, 87 KB, 219 KB and 442 KB took 7 ms, 168 ms, 853 ms and 5.1 seconds, and the 888 KB benchmark file took 34 seconds in a single run.
#include <iostream>
#include <string>
#include "parse.hpp"
#include "stringify.hpp"
int main()
{
const std::string text = R"(
{
// limits for the build farm
name: 'edge-proxy',
port: 0x1F90,
timeout: .75,
ceiling: Infinity,
tags: ['blue', 'green',],
})";
try
{
JSON5::Value v = JSON5::parse(text);
const auto &obj = std::get<JSON5::Object>(v);
std::cout << "name = " << std::get<std::string>(obj.at("name")) << "\n";
std::cout << "port = " << std::get<double>(obj.at("port")) << "\n";
JSON5::StringifyOptions opt;
opt.space = 2;
std::cout << JSON5::stringify(v, opt) << "\n";
}
catch (const JSON5::SyntaxError &e)
{
std::cerr << "line " << e.lineNumber << ", column " << e.columnNumber << ": " << e.what() << "\n";
return 1;
}
return 0;
}name = edge-proxy
port = 8080
{
ceiling: Infinity,
name: 'edge-proxy',
port: 8080,
tags: [
'blue',
'green',
],
timeout: 0.75,
} Note that the output keys are sorted, because objects are std::maps; the order from the file is gone.
mortie/json5cpp (on JsonCpp)
This one produces Json::Value objects, so it fits a code base that already uses JsonCpp. The parse function returns a bool and fills an error string; ParseConfig::maxDepth defaults to 100. The README says the parser passes the corpus plus the JSON test suite and reports "All tests pass" for its own 177 files, but in our run of the 114 official cases it accepted nine documents that must fail: a block comment left open after true, a lone decimal point, and seven octal-looking numbers such as 010 and 080. It also turned '\1' into the character 1. Valid input worked.
#include <iostream>
#include <sstream>
#include <string>
#include <json5cpp/json5cpp.h>
int main()
{
std::istringstream in(R"(
{ // build farm
name: 'edge-proxy',
port: 0x1F90,
timeout: .75,
tags: ['blue', 'green',],
})");
Json::Value root;
std::string err;
Json5::ParseConfig conf; // maxDepth defaults to 100
if (!Json5::parse(in, root, &err, conf))
{
std::cerr << "Invalid JSON5: " << err << "\n";
return 1;
}
std::cout << root["name"].asString() << " " << root["port"].asInt() << "\n";
Json5::SerializeConfig out;
out.indent = " ";
Json5::serialize(std::cout, root, out);
std::cout << "\n";
std::istringstream bad("{ a: 1 b: 2 }");
if (!Json5::parse(bad, root, &err))
std::cout << "error text: " << err << "\n";
return 0;
}edge-proxy 8080
{
name: "edge-proxy",
port: 8080,
tags: [
"blue",
"green",
],
timeout: 0.75,
}
error text: 1:8: Expected ',' or '}'json5pp
A single header with parse5() and stringify5(); the last commit on its main branch is from November 16, 2020. Four problems turned up. It reads infinity but rejects the capitalized Infinity the grammar requires (the corpus infinity.json5 files fail, and the source tests for a lowercase i). It writes the lowercase spelling back. A surrogate pair such as \ud83d\ude00 is decoded to two three-byte surrogate sequences (ED A0 BD ED B8 80), which is not valid UTF-8. stringify() prints numbers with the stream default of six significant digits, so 3.141592653589793 comes out as 3.14159; streaming the value through std::setprecision(17) gave 3.1415926535897931. And with GCC 15 the header fails to compile until you add #include <cstdint> before it.
#include <cstdint> // json5pp.hpp does not include it; needed with GCC 15
#include <iostream>
#include <string>
#include "json5pp.hpp"
int main()
{
const std::string text = "{ name: 'edge-proxy', port: 0x1F90, timeout: .75, tags: ['blue', 'green',], }";
try
{
json5pp::value v = json5pp::parse5(text);
std::cout << v["name"].as_string() << " " << v["port"].as_integer() << "\n";
std::cout << v.stringify5() << "\n";
std::cout << v.stringify5(json5pp::rule::space_indent<2>()) << "\n";
}
catch (const json5pp::syntax_error &e)
{
std::cerr << "syntax error: " << e.what() << "\n";
return 1;
}
// Capital-I Infinity, as the JSON5 grammar spells it:
try { json5pp::parse5("[Infinity]"); std::cout << "Infinity: accepted\n"; }
catch (const json5pp::syntax_error &e) { std::cout << "Infinity: " << e.what() << "\n"; }
try { json5pp::parse5("[infinity]"); std::cout << "infinity: accepted\n"; }
catch (const json5pp::syntax_error &e) { std::cout << "infinity: " << e.what() << "\n"; }
return 0;
}edge-proxy 8080
{"name":"edge-proxy","port":8080,"tags":["blue","green"],"timeout":0.75}
{
"name": "edge-proxy",
"port": 8080,
"tags": [
"blue",
"green"
],
"timeout": 0.75
}
Infinity: JSON syntax error: illegal character `I' in array
infinity: acceptedP-i-N/json5
A header-only library with reflection macros, the only one that maps a document straight onto your structs (see the next section). The repository has no release and its last commit on the main branch is May 3, 2021; compiling with GCC 15 required adding <cstring>, <limits> and <cmath> ahead of it. The parser rejects a document whose root is not an array or an object, so a bare number or string fails; that alone costs most of the corpus. Even with an array or object at the root, it read 0x1F90, 0xff and 0XFF as 0, turned -Infinity into an empty value and printed {a:,b:1}, wrapped 12345678901234567890 to -9223372036854775808, accepted [01] as 1 and [1e] as 1, and decoded \0 and \v to an empty string. Use it only for documents you wrote yourself, with plain decimal numbers.
Parsing into Your Own Structs
Only P-i-N/json5 does this for you. Its JSON5_MEMBERS macro lists the fields, and json5::from_file() fills them. This compiled with -std=c++20 and read a file with the same shape as the yyjson example but a decimal port, because of the hex bug above:
#include <cstring>
#include <cmath>
#include <limits>
#include <iostream>
#include <string>
#include <vector>
#include <json5/json5_input.hpp>
#include <json5/json5_output.hpp>
#include <json5/json5_reflect.hpp>
struct Upstream
{
std::string host;
int weight = 1;
JSON5_MEMBERS(host, weight)
};
struct Settings
{
std::string name;
int port = 0;
double timeout = 0;
std::vector<Upstream> upstreams;
JSON5_MEMBERS(name, port, timeout, upstreams)
};
int main(int argc, char **argv)
{
const char *path = argc > 1 ? argv[1] : "server.json5";
Settings s;
json5::error err = json5::from_file(path, s);
if (err)
{
std::cerr << path << ": " << json5::to_string(err) << "\n";
return 1;
}
std::cout << s.name << " on port " << s.port << ", timeout " << s.timeout << "\n";
for (const auto &u : s.upstreams)
std::cout << " " << u.host << " weight " << u.weight << "\n";
json5::writer_params wp;
wp.compact = true;
std::cout << json5::to_string(s, wp) << "\n";
return 0;
}edge-proxy on port 8080, timeout 0.75
10.0.0.5 weight 2
10.0.0.6 weight 1
{name:"edge-proxy",port:8080,timeout:0.75,upstreams:[{host:"10.0.0.5",weight:2},{host:"10.0.0.6",weight:1}]} With the other libraries, parse first and copy fields out by hand, as the yyjson program does. Three habits keep that safe. Check the type of every value you read: yyjson's accessors return 0 or NULL on a type mismatch, so a typo in a key name silently yields zero. Decide how to treat numbers up front, because JSON5 has one number type with no range. We fed 12345678901234567890 to each library: yyjson and the JsonCpp wrapper kept the exact value, json.h kept the digits as text, mqnc rounded it to 12345678901234567168, json5pp printed 1.23457e+19, and P-i-N wrapped it to a negative number. And pick a policy for duplicate keys, since the specification leaves it open: yyjson, json.h and P-i-N keep both entries, while json5pp, mqnc and the JsonCpp wrapper keep the last.
Writing JSON5
Strict JSON is already valid JSON5, so writing JSON5 matters only for the extras: unquoted keys, trailing commas, Infinity and NaN. None of the seven libraries keeps comments, so a load-and-save cycle deletes every comment in the file; an editing tool needs a library that keeps them, such as those on the implementations page. What each writer produced in our runs:
| Library | What the writer emits |
|---|---|
| yyjson | JSON. With default flags, a document holding infinity or NaN makes the write call return NULL; YYJSON_WRITE_ALLOW_INF_AND_NAN prints Infinity and NaN. A flag for trailing commas, YYJSON_WRITE_TRAILING_COMMAS, exists on the development branch but not in 0.13.0. |
| YAJL json5 branch | With yajl_gen_json5: unquoted identifier keys, +Infinity, NaN. |
| mqnc/json5cpp | Unquoted keys, single-quoted strings, trailing commas when indented, keys sorted. |
| mortie/json5cpp | Unquoted keys, double-quoted strings, trailing commas, keys sorted, tab indent by default. |
| json5pp | stringify5() printed quoted keys and double-quoted strings, the same as strict JSON for finite numbers; six significant digits unless you set the stream precision. |
| P-i-N/json5 | Unquoted keys and double-quoted strings; writer_params has compact and json_compatible options. |
| json.h | JSON only; infinity becomes 1.7976931348623158e308 and NaN becomes 0. |
The yyjson writer is the one to use when you need correct strings and exact numbers at speed; this program, built against 0.13.0, shows the Infinity behavior:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "yyjson.h"
int main(void) {
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_obj_add_str(doc, root, "name", "edge-proxy");
yyjson_mut_obj_add_int(doc, root, "port", 8080);
yyjson_mut_obj_add_real(doc, root, "timeout", 0.75);
yyjson_mut_obj_add_real(doc, root, "ceiling", INFINITY);
yyjson_mut_obj_add_real(doc, root, "unset", NAN);
yyjson_mut_val *tags = yyjson_mut_obj_add_arr(doc, root, "tags");
yyjson_mut_arr_add_str(doc, tags, "blue");
yyjson_mut_arr_add_str(doc, tags, "green");
/* Plain JSON write fails on Infinity and NaN. */
char *plain = yyjson_mut_write(doc, YYJSON_WRITE_PRETTY_TWO_SPACES, NULL);
printf("default flags: %s\n", plain ? plain : "(NULL, write failed)");
free(plain);
yyjson_write_flag flg = YYJSON_WRITE_PRETTY_TWO_SPACES
| YYJSON_WRITE_ALLOW_INF_AND_NAN;
yyjson_write_err err;
char *json = yyjson_mut_write_opts(doc, flg, NULL, NULL, &err);
if (!json) { fprintf(stderr, "write failed: %s\n", err.msg); return 1; }
printf("%s\n", json);
free(json);
yyjson_mut_doc_free(doc);
return 0;
}default flags: (NULL, write failed)
{
"name": "edge-proxy",
"port": 8080,
"timeout": 0.75,
"ceiling": Infinity,
"unset": NaN,
"tags": [
"blue",
"green"
]
}Error Handling
How you learn that a document is bad, and where, differs more than the grammar does. These are the messages each library gave for the same mistake, the missing comma in [1 2]. Plan your error path around what the library can tell you: a user who edits a config file wants a line and column.
| Library | Mechanism | Result for [1 2] |
|---|---|---|
| yyjson | Out-parameter with message and byte position; yyjson_locate_pos() converts to line and column | unexpected character, expected ',' or ']' at 3 |
| json.h | Result struct with a numeric code, offset, line and column | code 1 at offset 3, line 1 |
| YAJL branch | Error buffer filled by yajl_tree_parse(), with a context excerpt | parse error: after array element, I expect ',' or ']' |
| mqnc/json5cpp | Throws JSON5::SyntaxError with lineNumber and columnNumber | JSON5: invalid character '2' at 1:4 |
| mortie/json5cpp | Returns false, fills a string | 1:4: Expected ',' or ']' |
| P-i-N/json5 | Returns an error object; json5::to_string() formats it | comma expected at 1:4 |
| json5pp | Throws json5pp::syntax_error, message only | JSON syntax error: illegal character `2' in array |
Two warnings. First, a parser can fail outside its own error type: mqnc/json5cpp threw std::out_of_range for 1e400, so catch std::exception as well. Second, an empty file is an error in every library we tried, so a config loader must decide whether an empty or comment-only file means "use defaults" before calling the parser.
Safety and Speed
Deep nesting
A parser that recurses once per bracket can be crashed by a few hundred kilobytes of [. We fed each library N opening brackets followed by N closing ones with an 8 MB stack:
| Library | 1,000 | 10,000 | 100,000 | 1,000,000 and 10,000,000 |
|---|---|---|---|---|
| yyjson | OK | OK | OK | OK |
| json.h | OK | Error (limit 1,000) | Error | Error |
| mortie/json5cpp | Error (limit 100) | Error | Error | Error |
| YAJL branch | OK | OK | OK | Crash (segmentation fault) |
| json5pp | OK | OK | Crash | Crash |
| P-i-N/json5 | OK | OK | Crash | Crash |
| mqnc/json5cpp | OK | OK, 2.7 s | No answer in 60 s | No answer in 60 s |
"Error" is the safe outcome: json.h stops at its JSON_MAX_RECURSION macro (1,000 by default) and mortie/json5cpp at maxDepth. yyjson survived 10 million levels, which shifts the risk from the stack to memory. mqnc/json5cpp is slow rather than safe: at 20,000 levels it ran for 11 seconds and then crashed. Put your own cap on input size, and set YYJSON_READER_DEPTH_LIMIT at build time if documents come from outside. The security tutorial covers the same boundaries for JavaScript.
Text encoding
Strings are bytes, and not every library checks them. yyjson, mqnc/json5cpp and YAJL rejected the invalid byte 0xFF inside a string; json.h, json5pp and P-i-N accepted it, and mortie/json5cpp replaced it with U+FFFD. If the parsed string reaches a database, a filename or a terminal, validate it yourself when the library does not. The specification also asks parsers to warn about raw U+2028 and U+2029 inside strings; mqnc/json5cpp printed such a warning in our run, and the others stayed silent.
Parse speed
We generated one 888,177-byte document of 4,000 records with comments, single quotes, unquoted keys, decimals like .37 and +57., and trailing commas, then timed only the parse and free of the tree. The table shows the fastest run of several, in milliseconds. WSL2 timing is noisy; the same binaries varied by two to three times between rounds, so read the order of magnitude, not the decimals.
| Library | Fastest parse of 888 KB (ms) |
|---|---|
| yyjson 0.13.0 | 1.3 |
| json.h | 6.8 |
| P-i-N/json5 | 8.6 |
| YAJL branch (tree API) | 12 |
| json5pp | 16 |
| mortie/json5cpp (with JsonCpp) | 19 |
| mqnc/json5cpp | about 34,000 (one run) |
Build Integration
Everything except yyjson and YAJL is a header you copy into your tree: json.h, json5pp.hpp, the P-i-N json5/ folder, mqnc's src/ folder and mortie's json5cpp.h (which also needs JsonCpp). We built all of them with plain gcc and g++ command lines and did not run CMake, vcpkg or Conan ourselves, so the notes below come from the projects' own files.
- yyjson with CMake. Its build guide shows
add_subdirectory(vendor/yyjson)followed bytarget_link_libraries(your_target PRIVATE yyjson), and aFetchContentvariant that downloads a tag or master. The optionYYJSON_DISABLE_NON_STANDARDremoves the comment, trailing-comma and JSON5 flags to save about 10 percent of code size, so leave it off. - vcpkg. The
yyjsonport is at version 0.13.0, and itsnon-standardfeature ("Build with support for non-standard JSON") is on by default, so keep default features on. The port list also carriesyajl(a port of lloyd/yajl 2.1.0, whose history does not include the JSON5 branch) andjson5-parser, a JSON Spirit derivative that we did not test. - Conan Center. The recipe folder for
yyjsonlists 0.12.0 as its newest version, one behind GitHub, which is the first release with the JSON5 flag. We found no Conan Center recipe under the names json5pp, json5 or json.h. - Without libc. Since 0.13.0 yyjson has a
YYJSON_FREESTANDINGoption for targets with no C library, such as WebAssembly. - Newer compilers. GCC 15 no longer includes some headers transitively, which broke json5pp and P-i-N until we added the includes named above. Pin your toolchain in CI when you vendor an unmaintained header.
JSON5 in C and C++: Common Questions
Does the C++ standard library read JSON5?
No. Neither the C nor the C++ standard library has any JSON facility. Use one of the libraries above, or convert the text to JSON first with the online converter or the command-line tool.
Which library is best for a game or embedded config?
yyjson if you can use C: it is small, has no dependencies, can run without libc and passed the full corpus. Remember its 0.13.0 tab problem, and cap the nesting depth when the file is not yours.
Can I keep comments when I save a file?
Not with any of these seven; every one discards comments while parsing. Libraries that keep them exist for other languages, listed on the implementations page.
Why will json5pp or P-i-N not compile on my machine?
With GCC 15.2, json5pp needs #include <cstdint> placed before it, and P-i-N needs <cstring>, <limits> and <cmath>. The headers rely on other standard headers to include those for them, which newer libstdc++ versions no longer do.
Is it safe to parse untrusted JSON5 with these?
Only after limiting size and depth. Four of the seven crashed on deeply nested input, and one needed half a minute for a file under a megabyte. See the nesting and speed tables, and the security tutorial.
How do I write Infinity and NaN?
Use YYJSON_WRITE_ALLOW_INF_AND_NAN in yyjson or yajl_gen_json5 in the YAJL branch. Without them yyjson's write call fails, and json.h silently substitutes numbers. Remember that most strict JSON readers will refuse the output.
Sources
(14)
- ibireme/yyjson repository, with its API reference and build guide
- yyjson 0.12.0 release notes and 0.13.0 release notes
- mqnc/json5cpp repository and README
- mortie/json5cpp repository and README
- kimushu/json5pp repository and README
- P-i-N/json5 repository and README
- sheredom/json.h repository and README
- anjohnson/yajl, json5 branch, lloyd/yajl pull request 211, issue 252 and the EPICS Base commit merging JSON5 support into 7.0
- json5/json5-tests, commit ceb24d4
- The JSON5 specification
- SQLite JSON functions, including the JSON5 section
- RapidJSON (
reader.hparse flags), Boost.JSON (parse_options.hpp) and nlohmann/json (tags v3.12.0 and develop) - vcpkg yyjson port and Conan Center yyjson recipe
- libpdjson5, cj5 and judo (listed, not tested)
Last reviewed: November 29, 2026.
JavaScript
Python
TypeScript
Node.js
Rust
Java
C#
Ruby
Kotlin
Lua
Babel
Vite
webpack
ESLint
Prettier
VS Code
JetBrains