nlohmann / json

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

`unflatten` vs objects with number-ish keys #1575

Closed hoehrmann closed 4 years ago

hoehrmann commented 5 years ago

The documentation for flatten and unflatten should point out that JSON pointers as per RFC 6901 do not distinguish between arrays, and objects with number-ish strings as keys. There should also be a note about how unflatten decides whether to make an array or an object (e.g., it might just look at the first pointer, it might look at all of them, what happens for path elements like 1.0, 010, or 1E1).

json x = json::object({
  {"0", json::object({{"1", "2"}})},
  {"9", json::object({{"3", "4"}})},
});

is actually

{"0":{"1":"2"},"9":{"3":"4"}}

flattens to

{"/0/1":"2","/9/3":"4"}

and that unflattens to

[{"1":"2"},null,null,null,null,null,null,null,null,{"3":"4"}]
nlohmann commented 5 years ago

Good point! This should go into the documentation.

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

levinandrew commented 5 years ago

I think it would be helpful if there was a way to override the unflatten() behavior so that it didn't treat "0", "1", and "2" as list indices. In my application I actually want to use incrementing values from 0 as keys, and the automatic conversion to lists here makes unflatten() unusable for me

    // create JSON value
    json j_flattened =
    {
        {"/answer/everything", 42},
        {"/list/0", 1},
        {"/list/1", 0},
        {"/list/2", 2},
        {"/name", "Niels"},
    };

    // call unflatten()
    std::cout << std::setw(4) << j_flattened.unflatten() << '\n';

output:

{
    "answer": {
        "everything": 42
    },
    "list": [
        1,
        0,
        2
    ],
    "name": "Niels"
}
nlohmann commented 5 years ago

As the flatten and in particular the unflatten function are not really standardized, one could think about adding a parameter to not interpret numbers as strings.

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.