boostorg / json

A C++11 library for parsing and serializing JSON to and from a DOM container in memory.
https://boost.org/libs/json
Boost Software License 1.0
432 stars 96 forks source link

[Question] When using direct parsing, what happens if a key in the JSON is not in the struct? #1023

Closed DUOLabs333 closed 3 months ago

DUOLabs333 commented 3 months ago

Let's say we have struct B. B has three attributes. Now let's say I want to parse_into a string s with 4 keys, and 3 of them are attributes of B. Will the parsing succeed?

grisumbras commented 3 months ago

This is considered an error by the parser.

DUOLabs333 commented 3 months ago

Is there a way to turn it off? I have some JSON with some extra keys I use for logging purposes, but shouldn't matter to the underlying struct, as it could change. As far as I can tell, both glaze and daw_json_link support this, but I would like to not have to add another dependency (I'm only direct parsing for some of the JSON strings).

grisumbras commented 3 months ago

The way to allow missing keys is to use an optional as the member's type. E.g.

struct S {
  int n; // required
  std::optional<std::string> s; // not required
};

If that doesn't work for you, you can write a tag_invoke overload and convert with value_to.

DUOLabs333 commented 3 months ago

As it turns out, I can rework my system to not have any unused keys, but that could be useful if it later becomes a hard dependency. Thanks.