引言 **jsonpath在目前的工作中,主要用于『接口测试』中的字段提取。jsonpath通过『模糊查询


1.安装

  1. pip install jsonpath

2.使用说明

1.语法

  • jsonpath(数据源,’$..需提取的字段’)
  • 返回list类型数据

jsonPath.webp

2.示例

【题目】搜索“name=Allen”的相关信息

  1. from jsonpath import jsonpath
  2. jsonData = {"users": [
  3. {
  4. "id": 12,
  5. "name": "bosh",
  6. "No.": 1
  7. },
  8. {
  9. "name": "Allen",
  10. "No.": 34,
  11. "id": 13
  12. }
  13. ]}
  14. def hello1():
  15. search_name = 'Allen'
  16. res = jsonpath(jsonData, f"$..users[?(@.name=='{search_name}')]") # 提起name='Allen'的相关信息【返回list】
  17. print("Allen的相关信息:\t", res)
  18. # list转为dict
  19. resData = dict(res[0])
  20. print("dict数据:\t", resData)
  21. # 获取id
  22. id = resData.get('id')
  23. print("id=", id)
  24. if __name__ == '__main__':
  25. hello1()

image.png

3.进阶

【题目】取type字段的第一个值

  1. # -*- coding: utf-8 -*-
  2. """
  3. ====================================
  4. @File Name :jp.py
  5. @Time : 2022/9/23 16:30
  6. @Program IDE :PyCharm
  7. @Create by Author : 一一Cooling
  8. ====================================
  9. """
  10. from jsonpath import jsonpath
  11. def hello():
  12. data = {
  13. "firstName": "John",
  14. "lastName": "doe",
  15. "age": 26,
  16. "address": {
  17. "streetAddress": "naist street",
  18. "city": "Nara",
  19. "postalCode": "630-0192"
  20. },
  21. "phoneNumbers": [
  22. {
  23. "type": "iPhone",
  24. "number": "0123-4567-8888"
  25. },
  26. {
  27. "type": "home",
  28. "number": "0123-4567-8910"
  29. }
  30. ]
  31. }
  32. res = jsonpath(data, '$..[0][type]')
  33. print("res:\t", res)
  34. print("res-type:\t", type(res))
  35. if __name__ == '__main__':
  36. hello()

image.png