Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update json nodes in Python using jsonpath

I'm trying to modify json data based on a jsonpath expression:

{
    "SchemeId": 10,
    "nominations": [
        {
            "nominationId": 1
        }
    ]
}

Using something like

from jsonpath_ng import jsonpath, parse
jsonpath_expr = parse('$.SchemeId')
jsonpath_expr.find(data)
updated_json = jsonpath_expr.update(data, 'schemeId': 11)

I would like to update the SchemeId value, which should be possible using https://github.com/h2non/jsonpath-ng, however there are no examples. Is there a way to achieve this?

like image 866
3lysium Avatar asked Sep 17 '25 07:09

3lysium


1 Answers

I figured this out so I can share here. The update() method changes the values.

from jsonpath_ng import jsonpath, parse
import json
data = json.loads('''{"SchemeId": 10, "nominations": [ { "nominationId": 1 } ] }''')
jsonpath_expr = parse('$.SchemeId')
jsonpath_expr.find(data)
jsonpath_expr.update(data, 11)
print(json.dumps(data, indent=2))
like image 97
Vernon Sauder Avatar answered Sep 19 '25 08:09

Vernon Sauder