Python-json-使用jmespath来格式化处理json数据

一.安装

前提是json文件

pip install jmespth

二.查询一个key值

source=
    { 
	“a”: “foo”,
	 “b”: "bar",
	 "c": "baz"
    }
result = jmespath.search("a",source)
print(result)

三.通过层级访问

类似于jsonpath,通过.来表示路径的层级

source_1={"a": 
			{"b":
				 {"c":
				  	{"d":
				  		 "value"
				  		 }}}}
sub_result = jmespath.search("a.b.c",source_1)
print(sub_result)

输出为:{‘d’: ‘value’}

四.通过索引访问

通过索引来访问主要用于数组上

source_2 = ["a", "b", "c", "d", "e", "f"]
index_result = jmespath.search("[1]",source_2)
print(index_result)

结果为b

五.多个表达式综合使用

composite_exp = "a.b.c[0].d[1][0]"
source_3= {"a": {
  "b": {
    "c": [
      {"d": [0, [1, 2]]},
      {"d": [3, 4]}
    ]
  }
}}

composite_result = jmespath.search(composite_exp,source_3)
print(composite_result)

输出结果为1

六.Slicing 切片

和python切片类似:

source_4=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
slicing_exp = "[0:5]"
slicing_result = jmespath.search(slicing_exp,source_4)
print(slicing_result)

这个例子的结果为: [0, 1, 2, 3, 4]
基本的slicing的格式其实是: [start:stop:step]

七.投影

投影其实就是初始时定义好格式,然后按照格式的方式进行取值。
投影主要包括以下四种:

字典下的列表
列表下的字典
列表下的列表
字典下的字典

!!!注意:取列表用的[],取字典用的.

#1.字典下的列表
{
  "people": [
    {"first": "James", "last": "d"},
    {"first": "Jacob", "last": "e"},
    {"first": "Jayden", "last": "f"},
    {"missing": "different"}
  ],
  "foo": {"bar": "baz"}
}
query = people[:2].first
result:
[
  "James",
  "Jacob"
]
# 2. 列表下的字典
query = '''
        hotCommentTagStatistics[].{
        content:name,
        comment_count:count
    }
 #3. 列表下的列表
 [][0]
 #4 字典下的字典
 query = '''
        productCommentSummary.{
        goods_id:productId
        good_rate:goodRate
 }'''

jmespth API

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值