How do you get a JSON object from a string in nlohmann json?

Bob Galbil picture Bob Galbil · Apr 25, 2018 · Viewed 10.3k times · Source

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.

Answer

Tommaso Thea Cioni picture Tommaso Thea Cioni · Apr 25, 2018

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.