Skip to content

segfault when casting dictionary with circular reference to nlohmann::json #73

@dbaston

Description

@dbaston

Demonstrated by the following test case:

TEST(pybind11_caster_tojson, recursive_dict)
{
    py::scoped_interpreter guard;
    py::module m = create_module("test");

    m.def("to_json", &test_fromtojson);

    // Simulate calling this binding from Python with a dictionary as argument
    py::dict obj("number"_a=1234, "hello"_a="world");
    obj["recur"] = obj;
    py::print(obj); // ok

    nl::json j = m.attr("to_json")(obj); // segfault
}

This situation is detected by the json module:

>>> obj = {"number": 1234, "hello" : "world"}
>>> obj["recur"] = obj
>>> json.dumps(obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.10/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.10/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Circular reference detected

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions