Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"_json" user defined string-literal suffix #1994

Open
hattesen opened this issue Nov 14, 2023 · 1 comment
Open

"_json" user defined string-literal suffix #1994

hattesen opened this issue Nov 14, 2023 · 1 comment

Comments

@hattesen
Copy link

hattesen commented Nov 14, 2023

Adding a _json user defined string-literal suffix to ArduinoJson would provide a cleaner and more declarative source code at virtually no cost, and allow a JsonDocument to be created from a JSON string literal in one line of source code.

Example (from the current ArduinoJson documentation), generating a JsonDocument from a JSON string literal:

const char* json = "{\"hello\":\"world\"}";
JsonDocument doc;
deserializeJson(doc, json);

With a _json user defined string-literal suffix, this following source code would be functionally equivalent:

JsonDocument doc = "{\"hello\":\"world\"}"_json;

It removes all the boilerplate code when parsing (unmarshalling, deserializing) a literal JSON string. It would furthermore possibly allow the parsing to be performed at compile time, since all the required resources are available then.

Using a raw string literal for the JSON string literal, would make the example even simpler on the eye (and easier to type):

JsonDocument doc = R"({"hello":"world"})"_json;

This feature would add no additional runtime cost, would be fully backward compatible, and would not require much time to implement (I believe).

@hattesen hattesen changed the title "_json" user defined string-literal suffix could generate a JsonDocument from a literal JSON string in one line of source code "_json" user defined string-literal suffix Nov 14, 2023
@bblanchon
Copy link
Owner

Hi @hattesen,

I already considered adding the _json suffix but decided not to do it for two reasons.

The first is that it hides a call to deserializeJson(), and I'm afraid most people won't realize the impact on code size and speed. Indeed, deserializeJson() is not constexpr so it cannot be evaluated at compile-time. The fact that you think "this feature would add no additional runtime cost" proves that my intuition was correct.

The second reason is that, unlike nlohmann's library, ArduinoJson doesn't throw exceptions, so I don't have any way to report an error if anything goes wrong with the deserialization.

Best regards,
Benoit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants