全部 脚本手册 视频教程 图文教程 推荐教程

Json提取


访问 2060681

blob.png

一. 创建方法

在流程设计器中点右键,弹出右键菜单选择“变量处理”- “Json提取”。


. 功能介绍

使用JsonPath表达式从Json字符串中提取数据,JsonPath和XPath有点相似,但写法却是不一样的,这里我们对比一下XPath来学习JsonPath的用法。    先上一段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
    }
  }
}


比如我们要提取第一本书(book)的标题(title),如果我们把它当做是Xml的话,可以这样写
XPath:/store/book[1]/title
而使用JsonPath则是这样写
JsonPath:$.store.book[0].title
或者也可以这样写 $['store']['book'][0]['title']

JsonPath中的$相当于Xpath中的首字符"/",代表“根成员对象”,因为JSON结构通常是匿名的,不一定有一个“根成员对象”,所以这个$实际上是虚拟出来的,这里我们不用管它,知道他代表根对象就行了。而XPath中间部分的子操作符“/“,在JsonPath中则是用"."来表示,或者用第二种写法,用中括号"[]"来括住节点名称(节点名称要加上单引号)。
下面列个表格对比一下

XPath

JsonPath

说明

/

$

根对象/元素

.

@

当前对象/元素

/

. or []

子操作符

..

n/a

父操作符

//

..

递归查找所有级别的子级元素

*

*

通配符

@

查找指定属性,json中无属性的定义

[]

[]

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.

[start:end:step]

array slice operator borrowed from ES4.

[]

?()

用于过滤

()

脚本表达式,使用底层的脚本引擎。

()

Xpath中的分组



再看几个表达式的对比

XPath

JSONPath

Result

/store/book/author

$.store.book .author

the authors of all books in the store

//author

$..author

all authors

/store/*

$.store.*

all things in store, which are some books and a red bicycle.

/store//price

$.store..price

the price of everything in the store.

//book[3]

$..book[2]

the third book

//book[last()]


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


$..book[-1:]



the last book in order.

//book[position()<3]


$..book[0,1]


$..book[:2]



the first two books

//book[isbn]

$..book[?(@.isbn)]

filter all books with isbn number

//book[price<10]

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

filter all books cheapier than 10

//*

$..*

all Elements in XML document. All members of JSON structure.