JSLT
JSLT 是一种面向JSON的查询转换语言。作者是基于 jq, XPath, and XQuery启发设计JSLT语言。
JSLT能被用来:
- 一种用于在JSON中提取特定节点值的语法(.foo.bar[0]),
- 一种用于过滤/检查JSON ojbects的语法(starts-with(.foo.bar[0], "http://")),
- 一种用于在不同JSON格式中转换的语法
这里有一个示例:
{
"time": round(parse-time(.published, "yyyy-MM-dd'T'HH:mm:ssX") * 1000),
"device_manufacturer": .device.manufacturer,
"device_model": .device.model,
"language": .device.acceptLanguage,
"os_name": .device.osType,
"os_version": .device.osVersion,
"platform": .device.platformType,
"user_properties": {
"is_logged_in" : boolean(.actor."spt:userId")
}
}
Demo playground
(提供输入&JSLT表达式,计算输出)
链接
语法教程
函数文档
更多例子
Javaodc
API 介绍
快速参考
Operation | Explanation |
---|---|
. |
The context node |
.<name> |
Get value of key "<name>" inside an object |
.[<index>] |
Get value <index> inside an array |
.[<from> : <to>] |
Array slicing |
if (<expr>) <expr> else <expr> |
If test to decide which value to return |
let <name> = <expr> |
Define a variable |
$<name> |
Refer to a variable |
[for (<expr>) <expr>] |
Transform an array |
{for (<expr>) <expr> : <expr>} |
Transform an object |
def <name>(<name>, <name>...) <expr> |
Declare a function |
// <anything up to end of line> |
Comment |
{ <key> : <expr> } |
Object constructor |
{ <key> : <expr>, * : . } |
Specify one key, copy rest of input |
5 * 7 + 23.2 |
Arithmetic operations |
7 < 5 |
Comparators |
7 < 5 and .foo == "yes" |
Boolean operators |
使用库
在你的项目中,引入依赖
<dependency>
<groupId>com.schibsted.spt.data</groupId>
<artifactId>jslt</artifactId>
<version>0.1.11</version>
</dependency>
在运行时,JSLT只依赖于Jackson。
为了转换一个“JsonNode”到另一个钟,需要:
import com.schibsted.spt.data.jslt.Parser;
import com.schibsted.spt.data.jslt.Expression;
JsonNode input = ...;
Expression jslt = Parser.compileString(transform);
JsonNode output = jslt.apply(input);
其他更多可选方式, 参考 the
javadoc.
命令行
To run transforms on the command-line, first build with ./gradlew clean shadowJar
. Then you can run with:
java -cp build/libs/*.jar com.schibsted.spt.data.jslt.cli.JSLT transform.jslt input.json
The result is written to standard out.
网友评论