添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
不敢表白的小摩托  ·  Directory listing ...·  5 月前    · 
重感情的大熊猫  ·  PHP ...·  5 月前    · 
失望的鸡蛋面  ·  在Matlab ...·  6 月前    · 

JsonPath

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。

json示例数据

"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

如果有一个多层嵌套的复杂JSON,想要根据key-value 或下标 的方式去批量获取JSON数据里面的内容,是比较麻烦的。JsonPath模块就能很好的解决这个问题。

JsonPath 以一种简单的方法来提取给定的JSON的内容,JsonPath 支持多种编程语言,如JavaScript、Java、Python、和php。

JsonPath 语法规则

官方文档: https://goessner.net/articles/JsonPath/

JsonPath 提供的JSON解析功能非常强大,它提供了类似正则表达式的语法,基本上可以满足所有想要获得的JSON内容。

JsonPath "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 # 过滤出所有的包含isbn的书信息 data_book = jsonpath ( res , '$..book[?(@.isbn)]' ) print ( data_book ) # 获取店内所有书籍的作者 data_author = jsonpath ( res , '$.store.book[*].author' ) print ( data_author )
[{'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}]
['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']