akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.02k stars 807 forks source link

Replacing values in a arbitrary JSON file #660

Closed rcritten closed 10 months ago

rcritten commented 10 months ago

I want to be able to replace values in a JSON file where I don't know the format in advance, so I can't use json_unpack().

In experimenting I took inspiration from simple_parse.c to recursively find a given entry based on a name, sort of XPath-style.

I can find an arbitrary value, for the most part, but I haven't yet figured out out to replace the value.

When the recursive code finds the right json_t object pointing to the name/value pair to replace, it returns that.

I thought I could call:

json_object_set(new, "Value", json_string("foo"));
json_object_update(result, new);

But that doesn't update the the root.

If I instead use json_object_update(root, new)then the object is appended to the end of the JSON data rather than replacing it.

As a pythonic view in this case I'm trying to access data like this:

data['Input'][0]['Attribute'][0]['Value']

And then assigning a new value to that object.

rcritten commented 10 months ago

Switching to json_object_set_new() resolved the issue for me.