Python之JsonPath的使用

897 阅读1分钟

JsonPath的来源

正如XPath之于XML文档一样,JsonPath为Json文档提供了解析能力,通过使用JsonPath,你可以方便的查找节点、获取想要的数据,JsonPath是Json版的XPath。

JsonPath语法

JSONPATH描述
$根对象或元素
@当前对象或元素
. or []子元素操作符
..递归匹配所有子元素
*通配符,匹配所有对象或元素
[]下标运算法,JSONPATH索引从0开始
[,]连接运算符,将多个结果拼成数组返回,JSONPATH允许使用别名
[start:end:step]数组切片运算符
?()过滤器(脚本)表达式
()脚本表达式

注意:JsonPath中字符串使用单引号表示,例如:$.store.book[?(@.category=='reference')]中的'reference'

python中jsonpath模块的运用

首先安装jsonpath:pip install jsonpath

import jsonpath

author = jsonpath.jsonpath(data, 'jsonpath表达式')

注意:jsonpath表达式返回的都是列表。

操作实例(操作对象为json,非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
    }
  },
  "expensive": 10
}

点击此链接可在线验证jsonpath的正确性

  • 获取某个字段的所有值:
    例:获取json中store下book下的所有author值
$.store.book..author
or 
$.store.book[*].author

运行结果:

[  "Nigel Rees",  "Evelyn Waugh",  "Herman Melville",  "J. R. R. Tolkien"]
  • 切片获取某个数组的部分值:
    例:获取json中book数组的第二三本书
$..book[1:3]

运行结果:

[  {    "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  }]
  • 获取某个数组包含某字段的值:
    例:获取json中book数组中包含isbn的所有值
$..book[?(@.isbn)]

运行结果:

[  {    "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  }]
  • 获取某个数组满足某个判断条件的值:
    例:获取json中book数组中price小于等于10的值
$..book[?(@.price <= 10)]

运行结果:

[  {    "category": "reference",    "author": "Nigel Rees",    "title": "Sayings of the Century",    "price": 8.95  },  {    "category": "fiction",    "author": "Herman Melville",    "title": "Moby Dick",    "isbn": "0-553-21311-3",    "price": 8.99  }]
  • 获取数组中A字段满足某一条件的同级B字段值
    例:获取json中book数组中category为fiction书本的price
$..book[?(@.category == 'fiction')].price

运行结果:

[  12.99,  8.99,  22.99]