在工作中经常需要查找json里面的某个key的值,如果json层级太深,使用字典自带的get方法,比较麻烦。
这里演示一下第三方模块jmespath提取json键、值。
pip install jmespath
一、基本操作
查询key对应的value
import jmespath source = {"a": "foo", "b": "bar", "c": "baz"} result = jmespath.search('b', source) print(repr(result))
结果:‘bar’
.操作符
source1 = {"a": {"b": {"c": {"d": "value"}}}} result1 = jmespath.search('a.b.c', source1) print(repr(result1))
结果:{‘d’: ‘value’}
下标操作
仅用于数组
source_2 = ["a", "b", "c", "d", "e", "f"] index_result = jmespath.search("[1]",source_2) print(repr(index_result))
结果:‘b’
下标和.操作符混合操作
source3 = {"a": { "b": { "c": [ {"d": [0, [1, 2]]}, {"d": [3, 4]} ] } }} result3 = jmespath.search('a.b.c[0].d[1][0]',source3) print(repr(result3))
结果:1
切片
source_4 = ["a", "b", "c", "d", "e", "f"] result4 = jmespath.search("[1:3]",source_4) print(repr(result4))
结果:[‘b’, ‘c’]
二、投影
投影其实就是初始时定义好格式,然后按照格式的方式进行取值。
投影主要包括以下几种:
List Projections列表投影
Slice Projections切片投影
Object Projections对象投影
Flatten Projections正则投影
Filter Projections过滤条件投影
注意:取列表用[],取字典用.
# List and Slice Projections source5 = { "people": [ {"first": "James", "last": "d"}, {"first": "Jacob", "last": "e"}, {"first": "Jayden", "last": "f"}, {"missing": "different"} ], "foo": {"bar": "baz"} } result5 = jmespath.search('people[*].first', source5) print(result5)
结果:[‘James’, ‘Jacob’, ‘Jayden’]
# Object Projections # Whereas a list projection is defined for a JSON array, an object projection is defined for a JSON object. You can create an object projection using # the * syntax. source6 = { "ops": { "functionA": {"numArgs": 2}, "functionB": {"numArgs": 3}, "functionC": {"variadic": True} } } result6 = jmespath.search('ops.*.numArgs', source6) print(repr(result6))
结果:[3, 2]
# Filter Projections带过滤条件投影 # 格式[? <expression> <comparator> <expression>] # 支持 ==, !=, <, <=, >, >= # In this example we’re searching through the people array. Each element in this array contains a hash of two elements, and each value in the hash # is itself a hash. We’re trying to retrieve the value of the general key that contains an age key with a value above 20. source7 = { "people": [ { "general": { "id": 100, "age": 20, "other": "foo", "name": "Bob" }, "history": { "first_login": "2014-01-01", "last_login": "2014-01-02" } }, { "general": { "id": 101, "age": 30, "other": "bar", "name": "Bill" }, "history": { "first_login": "2014-05-01", "last_login": "2014-05-02" } } ] } result7 = jmespath.search("people[?general.age > `20`].general | [0]", source7) print(repr(result7))
结果:{‘id’: 101, ‘other’: ‘bar’, ‘age’: 30, ‘name’: ‘Bill’}
资料
官方:http://jmespath.org/examples.html
未经允许请勿转载:程序喵 » jmespath 提取 json数据