Skip to content

Modifications to nlohmann::json in Python Not Reflected in C++ Struct #72

@ma8tsch

Description

@ma8tsch

Hi there,
I am currently working on a project where I have a C++ struct containing a nlohmann::json object. After wrapping the struct with pybind11, the JSON object correctly translates to a Python dictionary. However, I am unable to modify the dictionary in Python and have the changes propagate back to the C++ object.

Minmal example

C++ Code

#include <pybind11/pybind11.h>
#include <pybind11_json.hpp>
#include <nlohmann/json.hpp>

typedef struct TTest
{
    double value;
    nlohmann::json json;

    TTest() : json(nlohmann::json::object()) {
        json['key_1'] = 0;
};

} TTest;

namespace py = pybind11;

PYBIND11_MODULE(libusrp, m)
{
    py::class_<TTest>(m, "TTest")
        .def(py::init<>())
        .def_readwrite("value", &TTest::value)
        .def_readwrite("json", &TTest::json);
}

Python Code

from mytest import TTest

# Create an instance of the class
data = TTest()

# Attempt to modify the JSON object
data.json["key_1"] = 1
data.json["new_key"] = 123
print(data.json) 
# Expected output: {'key_1': 1, 'new_key': 123}
# Actual output: {'key_1': 0}

# Workaround: Assign the JSON object to a local variable, modify it, and reassign it
json = data.json
json["key_1"] = 1
json["new_key"] = 123
data.json = json
print(data.json)
# Expected output: {'key_1': 1, 'new_key': 123}
# Actual output: {'key_1': 1, 'new_key': 123}

Expected Behavior

The data.json object in Python should reflect the changes made to it, without requiring the workaround of assigning and reassigning the object.

Actual Behavior

Changes made directly to data.json in Python are not propagated back to the json field in the underlying C++ object. The changes only take effect when the entire JSON object is reassigned after modification.

Additional Notes

  • pybind11 Version: 2.13.6
  • pybind_json: 0.2.14
  • nlohmann::json Version: 3.11.2
  • python Version: 3.12.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions