欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsonpath(xpath for json)

程序员文章站 2024-01-30 20:22:28
...

在接口测试中,我们需要断言接口的返回结果,若返回结果是json格式,就要一层一层的取json中的元素(r.json()[store][book][category]);若json层级较深,表达式就会很长。而jsonpath为我们提供了更加灵活、方便的获取元素的方式,下面举例说明jsonpath的使用。

官网地址:https://goessner.net/articles/JsonPath/

from jsonpath import jsonpath

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

#store.book下所有的author值
print(jsonpath(book_dict, '$.store.book[*].author'))

# 所有author的值
print(jsonpath(book_dict, '$..author'))

# store中所有的value
print(jsonpath(book_dict, '$.store.*'))

# store下所有price的值
print(jsonpath(book_dict, '$.store..price'))

# book中第3个元素
print(jsonpath(book_dict, '$..book[2]'))

# book中最后1个元素
print(jsonpath(book_dict, '$..book[(@.length-1)]'))
print(jsonpath(book_dict, '$..book[-1:]'))

# book中前两个元素
print(jsonpath(book_dict, '$..book[0,1]'))
print(jsonpath(book_dict, '$..book[:2]'))

# 所有含有isbn的元素
print(jsonpath(book_dict, '$..book[?(@.isbn)]'))

# 所有price小于10的元素
print(jsonpath(book_dict, '$..book[?(@.price<10)]'))

xpath与jsonpath对比

XPath JSONPath Description
/ $ the root object/element
. @ the current object/element
/ . or [] child operator
n/a parent operator
// recursive descent. JSONPath borrows this syntax from E4X.
* * wildcard. All objects/elements regardless their names.
@ n/a attribute access. JSON structures don’t have attributes.
[] [] subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
| [,] Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a [start:end:step] array slice operator borrowed from ES4.
[] ?() applies a filter (script) expression.
n/a () script expression, using the underlying script engine.
() n/a grouping in Xpath
相关标签: 接口测试 python