JsonPath使用和示例

简介: JsonPath使用和示例

1 简介

  • 官网:https://goessner.net/articles/JsonPath/
  • JsonPath 是一种简单的方法来提取给定JSON文档的部分内容;
  • JsonPath 支持多种编程语言,如JavascriptJavaPythonPHP

2 官方实例

  • 下边是官方给出的一个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
    }
  }
}

3 JsonPath与XPath语法对比

Xpath JsonPath 描述
/ $ 根节点
. @ 现行节点
/ . 或 [] 取子节点
取父节点,Jsonpath未支持
@ 根据属性访问,Jsonpath未支持,因为Json是个Key-value递归结构,不支持属性访问
* * 匹配所有元素节点
[] [] 迭代器标示(可以在里面做简单的迭代操作,如数组下标,根据内容选值等)
竖线 [,] 支持迭代器中做多选。连接操作符在XPath 结果合并其它结点集合。Jsonpath允许name或者数组索引。
[] ?() 支持过滤操作
[start: end: step] 数组分割操作从ES4借鉴
() 脚本表达式,使用底层脚本引擎。支持表达式计算
() Xpath分组;JsonPath不支持

4 实例说明JsonPath与XPath语法

  • 通过步骤2中的官方实例,简单看下JsonPathXPath语法的区别:
XPath JsonPath 描述
/store/book/author $.store.book[*].author 获取店内所有书籍的作者
//author $..author 获取所有作者
/store/* $.store.* 获取store的所有元素。所有的bookbicycle
/store//price $.store..price 获取store里面所有东西的价格
//book[3] $..book[2] 获取第三本书的所有信息
//book[last()] $..book[(@.length-1)] 或$..book[-1:] 获取最后一本书的所有信息
//book[position()<3] $..book[0,1] 或 $..book[:2] 获取前面两本书的所有信息
//book[isbn] $..book[?(@.isbn)] 过滤出所有的包含isbn的书信息
//book[price<10] $..book[?(@.price<10)] 过滤出价格低于10的书
//* $..* 获取所有元素

5 Python中JsonPath模块

pip install jsonpath

在这里插入图片描述

6 Python中JsonPath使用

# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/7/31 
# 文件名称:json_path.py
# 作用:jsonpath
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import jsonpath as jp

data = {
   
    "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
    }
  }
}
# 获取店内所有书籍的作者
author = jp.jsonpath(data, '$.store.book[*].author')
print(author)

# 输出
['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']
# 获取所有作者
all_aythor = jp.jsonpath(data, '$..author')
print(all_aythor)

# 输出
['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']
# 获取store的所有元素
book_bicycle = jp.jsonpath(data, '$.store.*')
print(book_bicycle)

# 输出
[[{
   
   '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}], {
   
   'color': 'red', 'price': 19.95}]
# 获取store里面所有东西的价格
price = jp.jsonpath(data, "$.store..price")
print(price)

# 输出
[8.95, 12.99, 8.99, 22.99, 19.95]
# 获取最后一本书的所有信息
last_book = jp.jsonpath(data, '$.store..book[-1:]')
print(last_book)

# 输出:
[{
   
   'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
# 过滤出价格低于10的书
p = jp.jsonpath(data, '$.store..book[?(@.price<10)]')
print(p)

# 输出:
[{
   
   '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}]

7 结合接口测试的实例

# 登陆接口
http://127.0.0.1/zentao/api.php/v1/tokens
data = {
   
   "account": "admin", "password": "123456"}
# 获取我的个人信息
http://127.0.0.1/zentao/api.php/v1/user
  • 实例:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/7/31 
# 文件名称:json_path.py
# 作用:jsonpath
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import jsonpath as jp
import requests
import json

base_url = "http://127.0.0.1/zentao/api.php/v1"
token_url = base_url + "/tokens"
info_rurl = base_url + "/user"

header = {
   
   "Content-Type": "application/json"}
data = {
   
   "account": "admin", "password": "ZenTao123456"}

r_data = json.dumps(data)
r = requests.post(url=token_url, data=r_data, headers=header)

r_token = jp.jsonpath(r.json(), '$..token')
print(r_token)

data1 = {
   
   "token": r_token[0]}
headers = dict(header, **data1)
r1 = requests.get(url=info_rurl, headers=headers)
print(r1.text)
  • 输出:
['14333e8b34595c5d22794e14c401a125']
{
   
   "profile":{
   
   "id":1,"company":0,"type":"inside","dept":0,"account":"admin","role":
{
   
   "code":"","name":""},
"realname":"admin","pinyin":"","nickname":"","commiter":"","avatar":null,"birthday":null,"gender":"f","email":"","skype":"","qq":"","mobile":"","phone":"","weixin":"","dingding":"","slack":"","whatsapp":"","address":"","zipcode":"","nature":null,"analysis":null,"strategy":null,"join":null,"visits":5,"visions":",rnd,lite,","ip":"127.0.0.1","last":"2023-07-31T06:14:45Z","fails":0,"locked":null,"feedback":"0","ranzhi":"","ldap":"","score":0,"scoreLevel":0,"resetToken":"","deleted":"0","clientStatus":"offline","clientLang":"zh-cn","admin":true,"superReviewer":false,"view":
{
   
   "account":"admin","programs":"","products":"","projects":"","sprints":""}}}
目录
相关文章
|
7月前
|
JSON 前端开发 JavaScript
JSON 必知必会
JSON 必知必会
118 0
|
5月前
|
SQL JSON JavaScript
什么是JSON PATH?
**JSON Path 概述** JSON Path 是一种查询JSON对象的语言,类似于XML的XPath。在JavaScript或PostgreSQL中,它简化了深层属性的访问。在PG中,传统的链式引用操作符如`-&gt;`可能繁琐,而JSON Path通过字符串路径表达式提供更简洁的访问方式。例如,`$.track.segments[0].HR`来获取心率数据。SQL/JSON Path Language允许通过`jsonb_path_query`等函数执行路径查询,支持通配符、条件检查和参数化路径。
|
7月前
|
存储 JSON JavaScript
JSON应用
JSON应用
65 4
|
JSON 前端开发 JavaScript
JSON小技巧
JSON小技巧
51 0
|
XML JSON Java
JSONPath 解析 JSON
JSONPath 解析 JSON
138 0
|
数据格式 JSON JavaScript
JSON是什么?
JSON 全称“JavaScript Object Notation”,译为“JavaScript 对象简谱”或“JavaScript 对象表示法”,是一种轻量级的、基于文本的、开放的数据交换格式。JSON 在 Web 开发领域有着举足轻重的地位,如果您想在 Web 开发领域大展身手的话,就必须了解 JSON。
|
JSON 数据格式
|
XML JSON JavaScript
json
json
82 0
|
存储 JSON JavaScript
JSON介绍
JSON介绍
220 0
|
存储 JSON 前端开发
下一篇
DataWorks