JsonPath基本用法

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

JsonPath语法

ps:JsonPath语法现在并没有形成统一的标准。

JsonPath语法要点:

$ 表示文档的根元素
@ 表示文档的当前元素
.node_name 或 ['node_name'] 匹配下级节点
[index] 检索数组中的元素
[start:end:step] 支持数组切片语法
* 作为通配符,匹配所有成员
.. 子递归通配符,匹配成员的所有子元素
(<expr>) 使用表达式
?(<boolean expr>)进行数据筛选

注意:

  • JsonPath的索引从0开始计数

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

JsonPath示例

{
	"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
		}
	}
}

python中使用jsonpath

import jsonpath

r={
  "errcode": 0,
  "errmsg": "ok",
  "taglist": [
    {
      "tagid": 2,
      "tagname": "修改后的标签名"
    },
    {
      "tagid": 3,
      "tagname": "test004"
    },
    {
      "tagid": 4,
      "tagname": "test005"
    },
    {
      "tagid": 5,
      "tagname": "test002"
    }
  ]
}

# 从jsno数据中取值,判断数据是否在json中
def test_json():
    res=jsonpath.jsonpath(r,'$..tagname')
    print(res)  # 返回一个数组
    print(len(res))
    assert 'test002' in res

结果:
['修改后的标签名', 'test004', 'test005', 'test002']
4


参考:
https://www.cnblogs.com/youring2/p/10942728.html
https://blog.csdn.net/xc_zhou/article/details/89500219
https://www.cnblogs.com/denise1108/p/10265911.html

原文地址:https://www.cnblogs.com/Uni-Hoang/p/13357419.html