nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.01k stars 6.63k forks source link

Exception on gcc but not apple clang #3986

Closed av4625 closed 1 year ago

av4625 commented 1 year ago

Description

When I parse json and use the operator[] with a string value it throws an exception saying it can't be used with an array even though there is no array in the json.

Reproduction steps

Get a value from json using operator[]. I think the code below explains the steps.

I am able to run the exact same code when compiled with apple clang 14.0.0 with no issue.

But when I run it when it was compiled with gcc/g++ 11.3 (for arm) I get the exception.

I use conan to get the library and set arch to armv7hf

Expected vs. actual results

I expect no exception to be thrown, but I get the following:

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error'
  what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array

Minimal code example

I store the json to a file like this:

const std::string one{"one_value"};
const std::string two{"two_value"};
const std::string three{"three_value"};

const nlohmann::json j = {
    {"one", one},
    {"two", two},
    {"three", three}
};

std::ofstream f("/path/to/file.json");
f << j;

I then get and parse the json like this:

// My struct just stores 3 std::string's
my_struct get()
{
    std::ifstream f("/path/to/file.json");
    const nlohmann::json j{nlohmann::json::parse(f)};
    std::cout << j() << std::endl

    return {
        track_id["one"],
        track_id["two"],
        track_id["three"]};
}

The json file correctly contains:

{"one":"one_value","two":"two_value","three":"three_value"}

Interestingly 🤨 the std::cout prints:

[{"one":"one_value","two":"two_value","three":"three_value"}]

Edit: I found that changing:

const nlohmann::json j{nlohmann::json::parse(f)};

to:

const nlohmann::json j = nlohmann::json::parse(f);

or:

const nlohmann::json j(nlohmann::json::parse(f));

fixes the issue. This should be the same thing in later cpp versions right? I compile both for c++17 when using apple clang and gcc 11.3 (for arm).

Error messages

No response

Compiler and operating system

Linux gcc/g++ 11.3 arm-linux-gnueabihf-gcc-11/arm-linux-gnueabihf-g++-11

Library version

3.11.2

Validation

nlohmann commented 1 year ago

The issue is in line

const nlohmann::json track_id{nlohmann::json::parse(f)};

which is interpreted differently by different compilers, see #2311.

Change it to

const nlohmann::json track_id = nlohmann::json::parse(f);

and it should work.