【爬虫】数据提取之JSONpath

安装

pip install jsonpath
# 或者
pip install jsonpath -i https://pypi.tuna.tsinghua.edu.cn/simple

使用

from jsonpath import jsonpath
ret = jsonpath(json_dict, 'jsonpath语法规则字符串')

jsonpath语法规则

JSONPath描述
$ 表示根元素
@当前元素
. or[]子元素
n/a 父元素,jsonpath未支持
..不管位置,选择符合条件的元素
*匹配所有元素节点
n/a根据属性访问,jsonpath未支持,因为json是一个key:value的递归结果,不需要属性访问。
[]迭代器标示,可以在里面做简单的迭代操作,如数组下标、根据内容选值等。
[,]支持迭代器做多选
?()支持过滤操作
()支持表达式计算
n/a分组,jsonpath未支持

举例

from jsonpath import jsonpath
book_dict = { 
  "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",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
res = jsonpath(book_dict, '$.store.book[*].author ')
print(res)
#索引从0开始 [索引]
res = jsonpath(book_dict , '$.store.book[0]')
print(res)
#根据条件筛选 ?(@.字段>数值)
# .. 直达选中字段
res = jsonpath(book_dict, '$..book[?(@.price>10)]')
print(res)

JSONPath描述
$.store.book[*].author 获取store中所有的book的作者
$..author 获取所有的作者
$.store.*获取store下的所有的元素
$.store..price 获取store中的所有的图书的价格
$..book[2]获取第三本书
$..book[(@.length-1)] | $..book[-1:] 获取最后一本书
$..book[0,1]| $..book[:2]获取前两本书
$..book[?(@.isbn)]获取有isbn的所有书
$..book[?(@.price>10)] 获取价格大于10的所有图书
$..*获取所有的数据
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

语音不识别

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值