Skip to content
Advertisement

Python: change json data according to provided paths (e.g. jsonpath)

I need a tool to modify json data with some arbitrary function applied only to specific paths expressed in some syntax (e.g. jsonpath, but may be any other). Key feature is to modify existing data structure, not to extract only some piece and then modify it. Is there something like I described?

For example we got the input data:

{
  "users": [
    {
      "group": "Admins", 
      "name": "John Smith"
    }, 
    {
      "group": "Users", 
      "name": "James Taylor"
    }
  ], 
  "groups": [ "Admins", "Users" ]
}

and I want to drop users’ last names. So, I need to apply the function like lambda x: x.split(' ')[0] to the jsonpath like $.users..name

as a result I want to get

{
  "users": [
    {
      "group": "Admins", 
      "name": "John"
    }, 
    {
      "group": "Users", 
      "name": "James"
    }
  ], 
  "groups": [ "Admins", "Users" ]
}

This is a very simple example, input data and path expression may be more sophisticated

Advertisement

Answer

I’ve found the solution using jsonpath-ng.

from jsonpath_ng import parse
input_data = json.load(file_with_json)
path = '$.users..name'
findings = parse(path).find(input_data)
for finding in findings:
    some_new_value = finding.value.split(' ')[0]
    finding.full_path.update(input_data, some_new_value)   

As a result input_data will contain an original dictionary but with updated values finded by path

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement