python之jmespath json解析使用例子

import jmespath
# 列表
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 所有元素
print(jmespath.search('[]', data) ) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(jmespath.search('[*]', data) ) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
jmespath.search('[:]', data)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 部分数据
print(jmespath.search('[5:8]', data) ) # 输出结果 [6, 7, 8]
jmespath.search('[::-1]', data)  #输出结果 [9, 8, 7, 6, 5, 4, 3, 2, 1]
jmespath.search('[8:1:-2]', data)  #输出结果 [9, 7, 5, 3]
# 字典
data = {"a": "foo", "b": "bar", "c": "baz"}
print(jmespath.search('a', data))  # 输出结果"foo"

data = {"a": {"b": {"c": {"d": "value"}}}}
print(jmespath.search('a.b.c.d', data) ) #输出结果 "value"
# 列表与字典
data = {"a": {
  "b": {
    "c": [
      {"d": [0, [1, 2]]},
      {"d": [3, 4]}
    ]
  }
}}
print(jmespath.search('a.b.c[0].d[1][0]', data) ) #输出结果 1
# *匹配
data = {
  "ops": {
    "functionA": {"numArgs": 2},
    "functionB": {"numArgs": 3},
    "functionC": {"variadic": True}
  }
}
print(jmespath.search('ops.*.numArgs', data))  #输出结果 [2, 3]

# 过滤
data = {
    "machines": [
        {"name": "a", "state": "running"},
        {"name": "b", "state": "stopped"},
        {"name": "b", "state": "running"}
    ]
}
jmespath.search("machines[?state=='running'].name", data)  #输出结果 ['a', 'b']

# 多个筛选条件

data = {
    "people": [
        {"first": "James", "last": "d"},
        {"first": "James", "last": "e"},
        {"first": "Jayden", "last": "f"},
        {"missing": "different"}
    ],
    "foo": {"bar": "baz"}
}
print(jmespath.search("people[?first=='James'] ", data) ) #输出结果 [{'first': 'James', 'last': 'd'}, {'first': 'James', 'last': 'e'}]
print(jmespath.search("people[?first=='James'] | [?last=='e'] ", data) ) #输出结果 [{'first': 'James', 'last': 'e'}]
print(jmespath.search("people[?first=='James'] | [?last=='e'] | [0]", data) ) #输出结果 {'first': 'James', 'last': 'e'}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值