引言 **jsonpath在目前的工作中,主要用于『接口测试』中的字段提取。jsonpath通过『模糊查询
1.安装
pip install jsonpath
2.使用说明
1.语法
- jsonpath(数据源,’$..需提取的字段’)
- 返回list类型数据
2.示例
【题目】搜索“name=Allen”的相关信息
from jsonpath import jsonpath
jsonData = {"users": [
{
"id": 12,
"name": "bosh",
"No.": 1
},
{
"name": "Allen",
"No.": 34,
"id": 13
}
]}
def hello1():
search_name = 'Allen'
res = jsonpath(jsonData, f"$..users[?(@.name=='{search_name}')]") # 提起name='Allen'的相关信息【返回list】
print("Allen的相关信息:\t", res)
# list转为dict
resData = dict(res[0])
print("dict数据:\t", resData)
# 获取id
id = resData.get('id')
print("id=", id)
if __name__ == '__main__':
hello1()
3.进阶
【题目】取type字段的第一个值
# -*- coding: utf-8 -*-
"""
====================================
@File Name :jp.py
@Time : 2022/9/23 16:30
@Program IDE :PyCharm
@Create by Author : 一一Cooling
====================================
"""
from jsonpath import jsonpath
def hello():
data = {
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
res = jsonpath(data, '$..[0][type]')
print("res:\t", res)
print("res-type:\t", type(res))
if __name__ == '__main__':
hello()