1

JSON for Modern C++ uses the following syntax:

json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;

and I was wondering how they are accomplishing this.

I don't understand the string literal _ json syntax.

Justin
  • 24,288
  • 12
  • 92
  • 142
sheridp
  • 1,386
  • 1
  • 11
  • 24

2 Answers2

5

C++11 added user defined literals to the language. Defining a user defined string literal would look like so:

MyType operator"" _my_udl(char const*, std::size_t);

It works almost exactly like a regular function call. When you have "some string"_my_udl, the compiler generates a call to your operator"" _my_udl with the string literal and size passed in.

This is what Niels Lohmann's json library is doing with _json; it's a UDL that is equivalent to a call to json::parse.

Justin
  • 24,288
  • 12
  • 92
  • 142
-1

On the docs for JSON for Modern C++: (serialisation / deserialisation)

Note that without appending the _json suffix, the passed string literal is not parsed, but just used as JSON string value. That is, json j = "{ \"happy\": true, \"pi\": 3.141 }" would just store the string "{ "happy": true, "pi": 3.141 }" rather than parsing the actual object.

Basically, if you don't put __json at the end, there's no way for the compiler to know that you're intending to store this as a JSON object, so it will just save it as a standard string

James Gupta
  • 871
  • 7
  • 15