Update json data with context in Python using jsonpath-ng

Viewed 844

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.

2 Answers

Here is example with lambda expression:

import json
from jsonpath_ng import parse

settings = '''{
  "choices": {
    "atm": {
      "cs": "Strom",
      "en": "Tree"
    },
    "bar": {
      "cs": "Dům",
      "en": "House"
    },
    "sea": {
      "cs": "Moře",
      "en": "Sea"
    }
  }
}'''

json_data = json.loads(settings)
pattern = parse('$.choices.*')

def magic(f: dict, to_lang='cs'):
    return f[to_lang]

pattern.update(json_data, 
               lambda data_field, data, field: data.update({field: magic(data[field])}))
json_data

returns

{
    'choices': {
        'atm': 'Strom',
        'bar': 'Dům',
        'sea': 'Moře'
    }
}

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
    }
  ]
}
Related