Skip to content

Behavior differences in operator[] object creation with a json_pointer #5357

Description

@nlohmann

Discussed in #5356

Originally posted by samcmill August 3, 2026
The following code throws a parse_error.106 exception due to the 01 token.

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    json obj = json::object();

    auto ptr = json::json_pointer("/a/b/01/d"); 

#ifdef INIT
    obj[json::json_pointer("/a/b")] = json::object();
#endif

    obj[ptr] = "value";

    std::cout << obj << std::endl; // prints {"a":{"b":{"01":{"d":"value"}}}}
}

However, if the first part of the JSON object up to 01 is pre-initialized, then the '01' token is treated as a string and the code runs successfully.

  1. Is this expected behavior? It seems unintuitive to me. Regardless, I am currently taking advantage of this behavior by walking the json_pointer and pre-initializing to handle cases like this.
  2. Would it make sense to have a mode where all json_pointer tokens are always treated as strings?

Related: #4446

Metadata

Metadata

Assignees

No one assigned

    Labels

    state: please discussplease discuss the issue or vote for your favorite option

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions