pythonjsonjsonpathjsonpath-ng

Update json data with context in Python using jsonpath-ng


following Update json nodes in Python using jsonpath, would like to know how one might update the JSON data given a certain context. So, say we pick the exact same JSON example:

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

But this time, would like to double the value of the original value, hence some lambda function is needed which takes into account the current node value.


Solution

  • No need for lambdas; for example, to double SchemeId, something like this should work:

    data = json.loads("""the json string above""")
    jsonpath_expr = parse('$.SchemeId')
    jsonpath_expr.find(data)
    val = jsonpath_expr.find(data)[0].value
    jsonpath_expr.update(data, val*2)
    print(json.dumps(data, indent=2))
    

    Output:

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