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

Question:

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

Asked By: Anton M.

||

Answers:

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

Answered By: Anton M.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.