skip to Main Content

need to find dict in [] , according specific value , but cannot find.
which I hope return value is
[{ "uid": {"type": "t2", "id": "world"}, "attrs": { "value": 456 } }]

import json
from jsonpath_ng.ext import parse

json_str = '''[
{
  "uid": {"type": "t1", "id": "hello"},
  "attrs": {
    "value": 123
  }
},
{
  "uid": {"type": "t2", "id": "world"},
  "attrs": {
    "value": 456
  }
}
]
'''
json_obj = json.loads(json_str)
[match.value for match in parse('$.[*].attrs[?value > 200]').find(json_obj)]

2

Answers


  1. Chosen as BEST ANSWER

    I find how to use jsonpath_ng.ext to `parse'

    [match.value for match in parse('$[?attrs.value > 200]').find(json_obj)]
    

  2. Try like this

    import json
    from jsonpath_ng import parse
    
    json_str = '''
    [
        {
            "uid": {"type": "t1", "id": "hello"},
            "attrs": {
                "value": 123
            }
        },
        {
            "uid": {"type": "t2", "id": "world"},
            "attrs": {
                "value": 456
            }
        }
    ]
    '''
    
    json_obj = json.loads(json_str)
    expr = parse('$.[*]')
    matches = [match.value for match in expr.find(json_obj) if match.value['attrs']['value'] > 200]
    print(matches)
    

    Output:

    [{'uid': {'type': 't2', 'id': 'world'}, 'attrs': {'value': 456}}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search