JsonPath usage and examples

1 Introduction

  • Official website: https://goessner.net/articles/JsonPath/ ;
  • JsonPathis a simple way to extract JSONparts of a given document;
  • JsonPathSupports multiple programming languages ​​such as Javascript, Java, Pythonand PHP.

2 official examples

  • Below is an official JSON example data to facilitate subsequent analysis:
{
    
     "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 and XPath syntax comparison

Xpath JsonPath describe
/ $ root node
. @ current node
/ . 或 [] Get child node
none Get the parent node, Jsonpathnot supported
@ none Access based on attributes Jsonpathis not supported because Jsonit is a Key-valuerecursive structure and does not support attribute access.
* * Match all element nodes
[] [] Iterator label (you can do simple iteration operations in it, such as array subscripting, selecting values ​​based on content, etc.)
vertical line [,] Supports multiple selections in iterators. The join operator XPathcombines other sets of nodes in the result. JsonpathAllows nameor array indexing.
[] ?() Support filtering operations
none [start: end: step] The array splitting operation is borrowed from ES4
none () Script expressions, using the underlying script engine. Support expression calculation
() none XpathGrouping; JsonPathnot supported

4 Examples to illustrate JsonPath and XPath syntax

  • Through the official example in step 2, let’s briefly look at the difference JsonPathwith XPaththe syntax:
XPath JsonPath describe
/store/book/author $.store.book[*].author Get the authors of all books in the store
//author $..author Get all authors
/store/* $.store.* Get storeall elements. all bookandbicycle
/store//price $.store..price Get storethe price of everything inside
//book[3] $..book[2] Get all the information on book three
//book[last()] $..book[(@.length-1)] 或$..book[-1:] Get all the information about the last book
//book[position()<3] $..book[0,1] 或 $..book[:2] Get all the information from the previous two books
//book[isbn] $..book[?(@.isbn)] Filter out all contained isbnbook information
//book[price<10] $..book[?(@.price<10)] Filter out books with price less than 10
//* $..* Get all elements

5 JsonPath module in Python

pip install jsonpath

Insert image description here

6 Use of JsonPath in Python

# -*- 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 Examples of combined interface testing

# 登陆接口
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
  • Example:
# -*- 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)
  • Output:
['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":""}}}

Guess you like

Origin blog.csdn.net/NoamaNelson/article/details/132020510