c++jsonstringnlohmann-json

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


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.


Solution

  • 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 these cases, you have to remove _json from the literal, but that makes second a string value hiding inside a JSON object.

    So, you call json::parse, like this:

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

    How to create a JSON object from a string.