11

I have a string that I would like to parse into a json, but _json doesn't seem to work every time.

#include <nlohmann/json.hpp>
#include <iostream>

using nlohmann::json;

int main()
{
    // Works as expected
    json first = "[\"nlohmann\", \"json\"]"_json;
    // Doesn't work
    std::string s = "[\"nlohmann\", \"json\"]"_json;
    json second = s;
}

The first part works, the second throws terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): [json.exception.type_error.302] type must be string, but is array.

Bob Galbil
  • 113
  • 1
  • 1
  • 4
  • Have you tried [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer/blob/master/doc/example2.md) it parses json directly into C++ objects. – Martin York Jul 11 '18 at 06:32

1 Answers1

17

Adding _json to a string literal instructs the compiler to interpret it as a JSON literal instead.

Obviously, a JSON object can equal a JSON value, but a string cannot.

In this cases, you have to remove _json from the literal, but that makes second a string value hiding inside a JSON object.

So, you also use json::parse, like this:

std::string s = "[\"nlohmann\", \"json\"]";
json second = json::parse(s);

How to create a JSON object from a string.

Tommaso Thea
  • 542
  • 1
  • 10
  • 18