JSONPath is a query language for JSON, similar to XPath for XML. AlertSite API endpoint monitors let you use JSONPath in assertions to specify the JSON fields that need to be verified.

JSONPath Notation

A JSONPath expression specifies a path to an element (or a set of elements) in a JSON structure. Paths can use the dot notation:

$.store.book[0].title

or the bracket notation:

$['store']['book'][0]['title']

The leading $ represents the root object or array and can be omitted. For example, $.foo.bar and foo.barare the same, and so are $[0].status and [0].status.

Other syntax elements are described below.

Expression Description
$ The root object or array.
.property Selects the specified property in a parent object.
['property']

Selects the specified property in a parent object. Be sure to put single quotes around the property name.

Tip: Use this notation if the property name contains special characters such as spaces, or begins with a character other than A..Za..z_.

[n] Selects the n-th element from an array. Indexes are 0-based.
[index1,index2,] Selects array elements with the specified indexes. Returns a list.
..property Recursive descent: Searches for the specified property name recursively and returns an array of all values with this property name. Always returns a list, even if just one property is found.
*

Wildcard selects all elements in an object or an array, regardless of their names or indexes. For example, address.* means all properties of the address object, and book[*] means all items of the book array.

[start:end]
[start:]

Selects array elements from the start index and up to, but not including, end index. If end is omitted, selects all elements from start until the end of the array. Returns a list.

[:n] Selects the first n elements of the array. Returns a list.
[-n:] Selects the last n elements of the array. Returns a list.
[?(expression)] Filter expression. Selects all elements in an object or array that match the specified filter. Returns a list.
[(expression)] Script expressions can be used instead of explicit property names or indexes. An example is [(@.length-1)] which selects the last item in an array. Here, length refers to the length of the current array rather than a JSON field named length.
@ Used in filter expressions to refer to the current node being processed.

Notes:

  • JSONPath expressions, including property names and values, are case-sensitive.

  • Unlike XPath, JSONPath does not have operations for accessing parent or sibling nodes from the given node.

Filters

Filters are logical expressions used to filter arrays. An example of a JSONPath expression with a filter is

$.store.book[?(@.price < 10)]

where @ represents the current array item or object being processed. Filters can also use $ to refer to the properties outside of the current object:

$.store.book[?(@.price < $.expensive)]

An expression that specifies just a property name, such as [?(@.isbn)], matches all items that have this property, regardless of the value.

Additionally, filters support the following operators:

Operator Description
== Equals to. 1 and '1' are considered equal. String values must be enclosed in single quotes (not double quotes): [?(@.color=='red')].
!= Not equal to. String values must be enclosed in single quotes.
> Greater than.
>= Greater than or equal to.
< Less than.
<= Less than or equal to.
=~

Match a JavaScript regular expression. For example, [?(@.description =~ /cat.*/i)] matches items whose description starts with cat (case-insensitive).

Note: Not supported at locations that use Ready! API 1.1.

!

Use to negate a filter: [?(!@.isbn)] matches items that do not have the isbn property.

Note: Not supported at locations that use Ready! API 1.1.

&& Logical AND, used to combine multiple filter expressions:

[?(@.category=='fiction' && @.price < 10)]

||

Logical OR, used to combine multiple filter expressions:

[?(@.category=='fiction' || @.price < 10)]

Note: Not supported at locations that use Ready! API 1.1.

Examples

For these examples, we will use a modified version of JSON from http://goessner.net/articles/JsonPath/index.html#e3:

{
  "store": {
    "book": [
      {
        "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
      },
      {
        "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
}

In all these examples, the leading $. is optional and can be omitted.

Expression Meaning
$.store.* All direct properties of store (not recursive).
$.store.bicycle.color

The color of the bicycle in the store.

Result: red

$.store..price
$..price

The prices of all items in the store.

Result: [8.95, 8.99, 22.99, 19.95]

$.store.book[*]
$..book[*]
All books in the store.
$..book[*].title

The titles of all books in the store.

Result: [Sayings of the Century, Moby Dick, The Lord of the Rings]

$..book[0]

The first book.

Result: [{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95}]

$..book[0].title

The title of the first book.

Result: Sayings of the Century

$..book[0,1].title
$..book[:2].title

The titles of the first two books.

Result: [Sayings of the Century, Moby Dick]

$..book[-1:].title
$..book[(@.length-1)].title

The title of the last book.

Result: [The Lord of the Rings]

The result is a list, because [-n:] always returns lists.

$..book[?(@.author=='J.R.R. Tolkien')].title

The titles of all books by J.R.R. Tolkien (exact match, case-sensitive).

Result: [The Lord of the Rings]

The result is a list, because filters always return lists.

$..book[?(@.isbn)] All books that have the isbn property.
$..book[?(!@.isbn)] All books without the isbn property.
$..book[?(@.price < 10)] All books cheaper than 10.
$..book[?(@.price > $.expensive)]

All expensive books.

$..book[?(@.author =~ /.*Tolkien/i)] All books whose author name ends with Tolkien (case-insensitive).
$..book[?(@.category == 'fiction' || @.category == 'reference')] All fiction and reference books.
$..* All members of the JSON structure beneath the root (child objects, individual property values, array items), combined into an array.

Considerations for JSONPath Expressions That Return Multiple Elements

JSONPath queries can return not just a single element, but also a list of matching elements. For example, given this JSON:

{
  "name": "Rose Kolodny",
  "phoneNumbers": [
    {
      "type": "home",
      "number": "954-555-1234"
    },
    {
      "type": "work",
      "number": "754-555-5678"
    }
  ]
}

the JSONPath expression

phoneNumbers[*].number

returns a list containing two phone numbers:

[954-555-1234, 754-555-5678]

Note that this is not a JSON array, it is just a comma-separated list of items where [ ] indicates the beginning and end of the list.

When using “equals” assertions against a list of matches, specify a list of expected values enclosed in [ ] and separated by a comma and one space:

[apples, 15, false, ["foo","bar"], {"status":"ok"}]

Standalone strings (like apples) should not have enclosing quotes, unless the quotes are part of the value.

Example

Values that are JSON arrays and objects keep inner quotes, but are minified with no spaces between their items: ["foo","bar"], not [ "foo" , "bar" ].

FAQ

How can I check that my JSONPath syntax is valid?

If you have Ready! API 1.9, you can create a test for your API endpoint, add a JSONPath Match assertion and test the syntax in the assertion editor there.

Otherwise, you can use http://jsonpath.herokuapp.com and check the results on the Jayway tab. However, the syntax used on this site may be slightly different from the one used in AlertSite.

See Also

API Assertions
Creating an API Endpoint Monitor
API Endpoint Monitor Settings

JSON JSONPath的更多相关文章

  1. Snack3 3.2 发布,轻量的Json+Jsonpath框架

    Snack3 是一个轻量的 JSON + Jsonpath 框架. 借鉴了 Javascript 所有变量由 var 申明,及 Xml dom 一切都是 Node 的设计.其下一切数据都以ONode表 ...

  2. Python | JSON 数据解析(Json & JsonPath)

    一.什么是JSON? JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js规范)的一 ...

  3. jsonpath读取json数据格式公用方法!!!

    import java.util.LinkedHashMap; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Pred ...

  4. JsonPath如何获取JSON数据中的值

    场景: 发送接口请求后,得到请求结果值是Json数据, 需要从Json数据信息中提取字段值. 响应值字符与字符之间有空格,导致用正则表达式方法提取比较麻烦,于是用java的JsonPath方法提取快速 ...

  5. python--爬虫之JSON于JsonPath

    JSON json的引入 在python中json作为一个内建库不需要额外安装,只需要使用import json执行引入 json模块的功能 在python中json模块提供了四个功能:dumps.d ...

  6. jmeter ---json几种读取方式,ArrayList循环读取

    在之前写过提取json数据格式的文章,这次对jmeter读取json数据格式进行整理. 举例一个接口的response 格式如下: { "data" : { "devic ...

  7. JMeter获取JSON内容

    source("D:\\apache-jmeter-3.0\\用例\\Test.java"); public static void f(){ String response_da ...

  8. 【JMeter】获取json响应报文中数组长度

    import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Predicate; import net.minidev.json.J ...

  9. jmeter beanshell遍历接口返回的json数组

    import java.util.LinkedHashMap; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Pred ...

随机推荐

  1. 2018.10.20 bzoj1079: [SCOI2008]着色方案(多维dp)

    传送门 dp妙题. f[a][b][c][d][e][last]f[a][b][c][d][e][last]f[a][b][c][d][e][last]表示还剩下aaa个可以用一次的,还剩下bbb个可 ...

  2. Spring boot 出现的时间

    Spring 4.0 ~ 4.3 不管商业操作如何,Spring还是继续发展, 2013年12月, Spring4.0 发布,这个版本开始支持JDK8 , 甚至比JDK8 的GA版本还要早3个月! 2 ...

  3. Initialization of bean failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'dataSource' of bean class [com.liuyang.jdbc.PersonDao]: No property 'dataSource

    这个错误是说我的启动失败了.这类问题要从配置文件中开始找原因,我用的是spring框架,所以我从application.中找的原因 然后对比路径,对比文件的命名和id,都没有问题,为什么会在启动的时候 ...

  4. excel绝对引用中间添加符号

    =F1&"_"&J1 绝对引用 相对引用 按F4 然后复制全部,选择性黏贴,值和数字即可

  5. NATAPP打穿内网

    前一篇博文写了ngrok作为内网穿透工具现在开始开始学习另外一种内 网穿透natapp(他也是基于ngrok的一种高速内网穿透服务)多的介绍就 不说了,开始进入正题. 第一步:先登录natapp官网( ...

  6. spring AbstractRoutingDataSource实现动态数据源切换

    使用Spring 提供的 AbstractRoutingDataSource 实现 创建 AbstractRoutingDataSource 实现类,负责保存所有数据源与切换数据源策略:public ...

  7. 2015 - 4- 21 iOS开发越狱环境的搭建1

    2015 - 4- 20   1. 越狱环境的搭建   http://www.iduuke.com/2030.html http://www.cnblogs.com/xiongwj0910/archi ...

  8. (线段树)敌兵布阵--hdu--1166 (入门)

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=1166 自己第一次在没有看题解AC出来的线段树,写的可能不是太好,再贴个学长的代码,学习一下 发现自己的U ...

  9. hbase使用MapReduce操作1(基本增删改查)

    操作代码 import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apach ...

  10. Android Sms短信发送

    界面布局: 具体代码: private void sendSms() { // 获取电话号码和短信内容 String number = number1.getText().toString(); St ...