Repository navigation
v2.2.0
cpp-yyjson 2.2.0 checks the JSON that it reads against the constraints of your types, and it writes the JSON Schema of those types. It also adds read policies, required keys and defaults, new variant types and new struct layouts. Validation and schema generation are opt-in. A type without annotations reads and writes JSON as in 2.1.0, except for the changes in Upgrading from 2.1. The upgrade guide gives the details of each change.
Upgrading from 2.1
Read each item that applies to your code. Each item gives the change and what to do.
Build
- With C++26 static reflection, the library now reads the annotations on a struct. A member setting on a struct, such as
struct [[=yyjson::skip]] S, fails to compile. 2.1.0 ignored it. Move such an annotation onto the member. A C++20 build needs no edit.
Reads and writes
- An untagged variant can select another alternative.
std::array<std::pair<std::string, int>, 1>now reads a JSON object (see Bug fixes). Thusstd::variant<std::array<std::pair<std::string, int>, 1>, std::map<std::string, int>>reads{"a":1}as the alternative 0. 2.1.0 gave the alternative 1. Put the map first, or use a tag. - A duration, such as
std::chrono::seconds, reads only an integer in the range of itsrep.read<std::chrono::seconds>("18446744073709551615")gave-1in 2.1.0. It now throwsyyjson::bad_castwithkind() == yyjson::error_kind::out_of_range. Catch this error where your input can hold such numbers. - If an alternative throws
yyjson::bad_cast, an untaggedstd::varianttries the next alternative. Another exception, such as astd::logic_errorfrom your caster, now leaves the read. To decline an alternative, throwyyjson::bad_castfrom the caster. - The library can skip a field caster of a variant alternative, or call it again to explain a failure. Do not rely on side effects of such a caster. Do them after the read selects the alternative.
- An enumeration written by name throws
yyjson::write_errorfor a value without a name, such asstatic_cast<Color>(7). 2.1.0 threwyyjson::bad_cast.yyjson::value(t)and the other DOM constructors do the same. Update thecatch, or write the enumeration withenum_format::name_or_integer. writethrowsstd::invalid_argumentfor an adjacent tag field beside an unnamedstd::monostate, also for an empty tag. With a string alternatives, 2.1.0 wrote{"kind":"s","d":null}, which it could not read back. Namestd::monostateinidsand set the tag to its name. Or omit the tag with a sentinel default, such asyyjson::field("kind", yyjson::default_, yyjson::min_length(1)).
Merge patches
- A patch can give a new value, which did not exist before the merge. Examples are a new member of a map, a value for an empty
std::optionaland a new alternative of a tagged variant.merge_intoremoves the members whose value isnullfrom each object of a new value.- A new member of a
std::map<std::string, yyjson::value>gets{"a":1}from{"k":{"z":null,"a":1}}. 2.1.0 kept"z":null. - A switch of a tagged variant reads
{"type":"circle","r":null}as a circle with the defaultr. 2.1.0 threwbad_cast. - A patch cannot set a member of a new object to
null. Assign thenullin code.
- A new member of a
- Consider a field
bodywithyyjson::adjacent_tag("t", ...).merge_intoof{"body":null}resetsbodyto its default alternative and keeps the tagt. Iftnames another alternative, the merge throwsbad_cast. 2.1.0 cleared the field. Give{"body":null,"t":null}to remove the value and its tag.
Diagnostics
-
The text of
yyjson::bad_cast::what()changed. It starts with the text ofmessage(). The path and the position follow, and a note for the developer ends it:2.1.0: int is not constructible from JSON string at /x/a/k (line 1, column 37, pos 36) 2.2.0: expected an integer, got a string at /x/a/k (line 1, column 37, pos 36); reading int -
With MSVC, a type name in
what()no longer starts withstruct,classorenum. -
A
bad_castthat your caster throws keeps its text inwhat(), and itsmessage()isthe value is not valid. -
A single
std::pair<std::string, int>still rejects a JSON object, and itsmessage()isexpected an array, got an object. -
If your code or your tests compare the text of
what(), comparekind(),path(),position()ormessage()instead.
Highlights
Constraints and JSON Schema
-
Constraints on fields. Annotations give the keywords of JSON Schema to a field.
read<T>,read_into,merge_intoandcast<T>()check them. A failed check throwsyyjson::bad_cast, andpath()names the value. A plainwrite(t)does not check. (validation)struct User { std::string name; int age = 0; std::vector<std::string> tags; }; template <> inline constexpr auto yyjson::annotations<User> = yyjson::annotate(yyjson::field("name", yyjson::min_length(1)), yyjson::field("age", yyjson::minimum(0), yyjson::maximum(150)), yyjson::field("tags", yyjson::max_items(8))); yyjson::read<User>(R"({"name":"Ann","age":200,"tags":[]})"); // bad_cast: the number is greater than the maximum 150 at /age (line 1, column 21, pos 20); reading the key "age" of User
The keyword table lists the value, array, map and struct keywords and the combinators. For
yyjson::patternandyyjson::pattern_properties, your program gives the regular expression engine as ayyjson::pattern_matcher<>. -
Check a value before you write it.
yyjson::validate(t)checks the JSON thatwritegives fort.yyjson::write(t, yyjson::with_validation)checks it before the write. (reference) -
JSON Schema. The new header
cpp_yyjson_schema.hppgivesyyjson::json_schema<T>().read<T>reads the JSON that is valid against this read schema.json_schema<T>(yyjson::write_direction)gives the write schema. The output ofwritefor a value thatyyjson::validateaccepts is valid against it. A short list of exceptions applies.yyjson::schema_collectioncollects the schemas of the types that you add for thecomponents/schemasof an OpenAPI 3.1 document. (JSON Schema)The schema requires the key of each field without a declared default. The initializer
int age = 0gives"default": 0, but it does not make the key optional.yyjson::default_does.std::cout << yyjson::json_schema<User>().write(yyjson::WriteFlag::PrettyTwoSpaces); // "User": { // "type": "object", // "properties": { // "name": { "type": "string", "minLength": 1 }, // "age": { "type": "integer", "minimum": 0, "maximum": 150, "default": 0 }, // ... // }, // "required": ["name", "age", "tags"] // }
-
merge_intochecks the merged JSON. For a struct with constraints,merge_intochecks the object after the merge, if the library can write the old value. If it cannot, it checks only the values of the patch. (validation)
Policies, defaults and errors
- Read policies.
yyjson::reject_unknown_keys,reject_missing_keys,reject_null_as_missingandreject_duplicatesmake a read stricter.yyjson::strictgives the last three, so it still accepts unknown keys. Addyyjson::reject_unknown_keysto reject them. Give a policy to one call, as inyyjson::read<User>(json, yyjson::strict), or to one type in its annotations. (validation) - Required keys and defaults.
yyjson::requiredmakes a read fail when the key is missing.yyjson::default_andyyjson::default_from<f>declare the default of a field, andwriteleaves out a value equal to it.yyjson::emit_defaultswrites such values. Empty optionals and sentinel defaults stay omitted. (conversions) - Errors for clients and for programs.
bad_cast::message()gives the reason in the words of JSON, such asthe number is greater than the maximum 150. It holds no C++ type name and no input text, so a server can send it to a client.bad_cast::kind()classifies the failure, such aserror_kind::missing_key. Forerror_kind::keyword,keyword()names the keyword, such asmaximum. When no alternative of a variant reads a value, the error gives the reason of each alternative. (reference)
Other additions
- Variants with rules.
yyjson::any_of_variantselects the first alternative that reads the value, as an untaggedstd::variantdoes.yyjson::one_of_variantrequires exactly one alternative whose read schema the value matches.yyjson::altgives an alternative its own constraints. (conversions) - Named null alternative.
yyjson::adjacent_tagcan namestd::monostateinids. That name reads and writesnullwith the tag, such as{"kind":"none","d":null}. (conversions) - New types and layouts.
yyjson::indirect<T>holds a recursive field, such as the children of a tree node. (reference)yyjson::nullable<T>writesnullfor no value. Astd::optionalfield leaves out the key instead. (reference)yyjson::transparentwrites a struct of one field as the value of that field. (conversions)yyjson::as_arraywrites a struct as a JSON array of its fields. (conversions)yyjson::pattern_propertieskeeps the keys that match a pattern.yyjson::extra_keyskeeps the other keys that no field names. (validation)yyjson::with_casterconverts one field with a caster. The library converts the other fields of that type. (conversions)
- More C++26 annotations. With C++26 static reflection, every setting of
yyjson::fieldcan be an annotation on the member, such as[[=yyjson::minimum(0)]]. The settings of a type can be annotations on the struct, such asstruct [[=yyjson::transparent]] UserId. (conversions)
Bug fixes
- Clang 21.1 failed to compile any program that included the header of 2.1.0. 2.2.0 compiles with Clang 21.1.
writegives astd::arrayor a C array of key-value pairs as a JSON object, but 2.1.0 could not read that object back.read<T>,read_intoandcast<T>()now read it.emplace_backandemplace_frontof a mutable array now compile with an initializer list andyyjson::copy_string.- A duration out of the range of its
repnow throwsyyjson::bad_cast, and the read schema gives that range. 2.1.0 gave a wrong value.
Performance
The measurements used GCC 15.2 with -O3. Each read took a vector of 1,000 objects {"x":"s"} into std::variant<A, B>. A has an int x, and B has a std::string x.
| Case | 2.1.0 | 2.2.0 |
|---|---|---|
Direct read<T>, per element |
1,435 ns | 23 ns |
| DOM parse and cast, per element | 1,591 ns | 28 ns |
Failing input [{"x":null}], direct read, error caught |
7.40 µs | 18.27 µs |
Failing input [{"x":null}], cast of an existing DOM, what() called |
7.80 µs | 10.93 µs |
A failing read costs more, because the error gives the reason of each alternative.
Build
cmake --installalso installscpp_yyjson_schema.hpp. That header needs no other library. Only the tests of the repository need jsoncons, which the vcpkg manifest lists.
See the upgrade guide for the details of each change.