Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ma8tsch opened this issue Nov 25, 2024 · 0 comments
Open

Comments

@ma8tsch
Copy link

ma8tsch commented Nov 25, 2024

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant