3

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.

Eyal
  • 48
  • 7

2 Answers2

4

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
    }
  ]
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
3

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'
    }
}
Dingo
  • 2,656
  • 1
  • 19
  • 16