Search code examples
pythonjsonjsonpath

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?


Solution

  • 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))