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.

2 Answers 2

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
    }
  ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, is it also possible to delete a node using jsonpath_ng?
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'
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.