JsonPath根据值查找元素(Python)

JsonPath根据值查找元素(Python)

实战实例

  1. 需求:从数组json列表中,根据具体数组中的某一个json其中一个字段来取另一个字段值。
  2. 示例数据如下:
{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction-1",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction-2",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      },
	  .............
	  .............
	  .............
    ]
  }
}
  1. 获取 数据列表中 “category” = “fiction” 这个 book 对象,jsonpath写法如下:
$..*[?(@.category=='reference')]
  1. 结果如下:
    在这里插入图片描述
  2. 要获 对象的另一个属性,就简单了,直接 .price 即可。
    在这里插入图片描述
    在线实验工具:jsonpath在线工具

安装

pip install  jsonpath

基本知识

  1. 官方:https://goessner.net/articles/JsonPath/
  2. https://juejin.cn/post/6850418109473783816
  3. https://blog.youkuaiyun.com/myt2000/article/details/120757692

高级知识

根据文本内容查找,获取 节点路径

  • JsonPaht 表达式:
"$..*[?(@=='12M7qEpkl85g00')]"
  • 示例
jsonpath(json_obj, "$..*[?(@=='12M7qEpkl85g00')]",result_type="IPATH")

返回值:

[['items', '0', 'userId']]
  • 路径转换为表达式, 使用引号,可解决中间有空格问题
$.'items'.'0'.'userId'
or
$['items']['0']['userId']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值