Skip to content

Inconsistency between operator[] and push_back #203

@nlohmann

Description

@nlohmann

Situation

When operator[] is called on a null value with a string_t argument, the value is silently converted to an object. When operator[] is called on a null value with an integer argument, an exception is thrown.

This feels inconsistent compared to push_back: When push_back is called on a null value, the value is silently converted to an object (if the argument was a string_t/json-pair) or an array (if the argument was a json value).

Proposal

I would propose changing operator[] to always convert a null value to an array. Thereby, the following code would be possible:

json j;
j[2] = 17;
std::cout << j << '\n';

And the output would be [null,null,17].

Rationale

This would then behave exactly like the following code:

json j = json::array();
j[2] = 17;
std::cout << j << '\n';

This code already works as described: Calling operator[] on an array, but with an integer argument out of bounds extends the array accordingly with null values.

What do you think?

Metadata

Metadata

Assignees

Labels

solution: invalidthe issue is not related to the library

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions