Skip to content

Object deserialized as array #2204

Description

@martin-vitek

What is the issue you have?

When initializing basic_json from std::string (or using basic_json::parse()), then main JSON object is parsed as array, not as object. Deserialization using std::stringstream with >> operator or with _json works as expected.

Please describe the steps to reproduce the issue.

  1. Create std::string with specified JSON string
  2. Create basic_json object and initialize it with this string
  3. Dump json object, or try to access value via name

Can you provide a small but working code example?

std::string json_string = R"(
{
    "serviceVersion":"1.0",
    "resultCode":
    {
        "code":0,
        "text":"OK"
    },
    "challenge":"sdfg45sdg45",
    "authenticationType":0,
    "challengeId":"dsv1d51df5-dasfv551v1-asdv155551"
})";

auto json_object {nlohmann::json::parse(json_string)};
std::cout << json_object.dump() << '\n';
std::cout << json_object["challenge"] << '\n';

What is the expected behavior?

{"authenticationType":0,"challenge":"sdfg45sdg45","challengeId":"dsv1d51df5-dasfv551v1-asdv155551","resultCode":{"code":0,"text":"OK"},"serviceVersion":"1.0"}
"sdfg45sdg45"

And what is the actual behavior instead?

[{"authenticationType":0,"challenge":"sdfg45sdg45","challengeId":"dsv1d51df5-dasfv551v1-asdv155551","resultCode":{"code":0,"text":"OK"},"serviceVersion":"1.0"}]
terminate called after throwing an instance of 'nlohmann::detail::type_error'
  what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array

Which compiler and operating system are you using?

  • Compiler: GCC 10.1.1
  • Operating system: Fedora 32
  • Language version: C++20

Which version of the library did you use?

  • latest release version 3.8.0
  • other release - please state the version: ___
  • the develop branch

Metadata

Metadata

Assignees

No one assigned

    Labels

    solution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions