Skip to content

v2.2.0

Choose a tag to compare

@yosh-matsuda yosh-matsuda released this 22 Nov 09:28
· 117 commits to main since this release

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). Thus std::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 its rep. read<std::chrono::seconds>("18446744073709551615") gave -1 in 2.1.0. It now throws yyjson::bad_cast with kind() == yyjson::error_kind::out_of_range. Catch this error where your input can hold such numbers.
  • If an alternative throws yyjson::bad_cast, an untagged std::variant tries the next alternative. Another exception, such as a std::logic_error from your caster, now leaves the read. To decline an alternative, throw yyjson::bad_cast from 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_error for a value without a name, such as static_cast<Color>(7). 2.1.0 threw yyjson::bad_cast. yyjson::value(t) and the other DOM constructors do the same. Update the catch, or write the enumeration with enum_format::name_or_integer.
  • write throws std::invalid_argument for an adjacent tag field beside an unnamed std::monostate, also for an empty tag. With a string alternative s, 2.1.0 wrote {"kind":"s","d":null}, which it could not read back. Name std::monostate in ids and set the tag to its name. Or omit the tag with a sentinel default, such as yyjson::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::optional and a new alternative of a tagged variant. merge_into removes the members whose value is null from 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 default r. 2.1.0 threw bad_cast.
    • A patch cannot set a member of a new object to null. Assign the null in code.
  • Consider a field body with yyjson::adjacent_tag("t", ...). merge_into of {"body":null} resets body to its default alternative and keeps the tag t. If t names another alternative, the merge throws bad_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 of message(). 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 with struct , class or enum .

  • A bad_cast that your caster throws keeps its text in what(), and its message() is the value is not valid.

  • A single std::pair<std::string, int> still rejects a JSON object, and its message() is expected an array, got an object.

  • If your code or your tests compare the text of what(), compare kind(), path(), position() or message() instead.

Highlights

Constraints and JSON Schema

  • Constraints on fields. Annotations give the keywords of JSON Schema to a field. read<T>, read_into, merge_into and cast<T>() check them. A failed check throws yyjson::bad_cast, and path() names the value. A plain write(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::pattern and yyjson::pattern_properties, your program gives the regular expression engine as a yyjson::pattern_matcher<>.

  • Check a value before you write it. yyjson::validate(t) checks the JSON that write gives for t. yyjson::write(t, yyjson::with_validation) checks it before the write. (reference)

  • JSON Schema. The new header cpp_yyjson_schema.hpp gives yyjson::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 of write for a value that yyjson::validate accepts is valid against it. A short list of exceptions applies. yyjson::schema_collection collects the schemas of the types that you add for the components/schemas of an OpenAPI 3.1 document. (JSON Schema)

    The schema requires the key of each field without a declared default. The initializer int age = 0 gives "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_into checks the merged JSON. For a struct with constraints, merge_into checks 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_missing and reject_duplicates make a read stricter. yyjson::strict gives the last three, so it still accepts unknown keys. Add yyjson::reject_unknown_keys to reject them. Give a policy to one call, as in yyjson::read<User>(json, yyjson::strict), or to one type in its annotations. (validation)
  • Required keys and defaults. yyjson::required makes a read fail when the key is missing. yyjson::default_ and yyjson::default_from<f> declare the default of a field, and write leaves out a value equal to it. yyjson::emit_defaults writes 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 as the 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 as error_kind::missing_key. For error_kind::keyword, keyword() names the keyword, such as maximum. 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_variant selects the first alternative that reads the value, as an untagged std::variant does. yyjson::one_of_variant requires exactly one alternative whose read schema the value matches. yyjson::alt gives an alternative its own constraints. (conversions)
  • Named null alternative. yyjson::adjacent_tag can name std::monostate in ids. That name reads and writes null with 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> writes null for no value. A std::optional field leaves out the key instead. (reference)
    • yyjson::transparent writes a struct of one field as the value of that field. (conversions)
    • yyjson::as_array writes a struct as a JSON array of its fields. (conversions)
    • yyjson::pattern_properties keeps the keys that match a pattern. yyjson::extra_keys keeps the other keys that no field names. (validation)
    • yyjson::with_caster converts 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::field can be an annotation on the member, such as [[=yyjson::minimum(0)]]. The settings of a type can be annotations on the struct, such as struct [[=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.
  • write gives a std::array or a C array of key-value pairs as a JSON object, but 2.1.0 could not read that object back. read<T>, read_into and cast<T>() now read it.
  • emplace_back and emplace_front of a mutable array now compile with an initializer list and yyjson::copy_string.
  • A duration out of the range of its rep now throws yyjson::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 --install also installs cpp_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.