一个计算机技术爱好者与学习者

0%

JSONPath入门篇

1. JSONPath简介

JSON (JavaScript Object Notation) allows for easy interchange of data, often between a program and a database.

JSONPath is a query language for JSON, similar to XPath for XML.

如上,json是一种常用的数据格式,jsonpath是json的查询语言,类似于XPath和SQL。

jsonpath在线测试:JSONPath Online Evaluator

2. YAML和JSON

YAML和JSON可以相互转化,详情参考《YAML语言》

3. JSONPath语法

摘自 json-path/JsonPath

3.1. 操作符

OperatorDescription
$The root element to query. This starts all path expressions.
@The current node being processed by a filter predicate.
*Wildcard. Available anywhere a name or numeric are required.
..Deep scan. Available anywhere a name is required.
.<name>Dot-notated child
['<name>' (, '<name>')]Bracket-notated child or children
[<number> (, <number>)]Array index or indexes
[start:end]Array slice operator
[?(<expression>)]Filter expression. Expression must evaluate to a boolean value.

3.2. 函数

Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression.
The function output is dictated by the function itself.

FunctionDescriptionOutput
min()Provides the min value of an array of numbersDouble
max()Provides the max value of an array of numbersDouble
avg()Provides the average value of an array of numbersDouble
stddev()Provides the standard deviation value of an array of numbersDouble
length()Provides the length of an arrayInteger
sum()Provides the sum value of an array of numbersDouble

3.3. 过滤器

Filters are logical expressions used to filter arrays. A typical filter would be [?(@.age > 18)] where @ represents the current item being processed. More complex filters can be created with logical operators && and ||. String literals must be enclosed by single or double quotes ([?(@.color == 'blue')] or [?(@.color == "blue")]).

OperatorDescription
==left is equal to right (note that 1 is not equal to ‘1’)
!=left is not equal to right
<left is less than right
<=left is less or equal to right
>left is greater than right
>=left is greater than or equal to right
=~left matches regular expression [?(@.name =~ /foo.*?/i)]
inleft exists in right [?(@.size in [‘S’, ‘M’])]
ninleft does not exists in right
subsetofleft is a subset of right [?(@.sizes subsetof [‘S’, ‘M’, ‘L’])]
anyofleft has an intersection with right [?(@.sizes anyof [‘M’, ‘L’])]
noneofleft has no intersection with right [?(@.sizes noneof [‘M’, ‘L’])]
sizesize of left (array or string) should match right
emptyleft (array or string) should be empty

3.4. DEMO

Given the json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"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
}
},
"expensive": 10
}
JsonPath (click link to try)Result
$.store.book[*].authorThe authors of all books
$..authorAll authors
$.store.*All things, both books and bicycles
$.store..priceThe price of everything
$..book[2]The third book
$..book[-2]The second to last book
$..book[0,1]The first two books
$..book[:2]All books from index 0 (inclusive) until index 2 (exclusive)
$..book[1:2]All books from index 1 (inclusive) until index 2 (exclusive)
$..book[-2:]Last two books
$..book[2:]Book number two from tail
$..book[?(@.isbn)]All books with an ISBN number
$.store.book[?(@.price < 10)]All books in store cheaper than 10
$..book[?(@.price <= $[‘expensive’])]All books in store that are not “expensive”
$..book[?(@.author =~ /.*REES/i)]All books matching regex (ignore case)
$..*Give me every thing
$..book.length()The number of books

4. kubectl + JSONPath

kubelet支持JSONPath,具体参考JSONPath 支持
除了标准jsonpath语法外,kubernetes jsonpath模板还额外支持以下语法:

  • ""双引号来引用JSONPath表达式中的文本
  • 使用range和end来遍历集合
  • 使用负数来从尾部索引集合

例如查看node的cpu信息:

1
2
3
4
5
6
7
8
kubectl get nodes -o=jsonpath='{.items[*].metadata.name}'
kubectl get nodes -o=jsonpath='{.items[*].status.capacity.cpu}'
kubectl get nodes -o=jsonpath='{.items[*].metadata.name}{.items[*].status.capacity.cpu}'
kubectl get nodes -o=jsonpath='{.items[*].metadata.name}{"\n"}{.items[*].status.capacity.cpu}'
kubectl get nodes -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.capacity.cpu}{end}'
kubectl get nodes -o=custom-columns=NODE:.metadata.name,CPU:.status.capacity.cpu
kubectl get nodes --sort-by=.metadata.name
kubectl get nodes --sort-by=.status.capacity.cpu

5. 特殊说明

如果key中包含点.,例如key为config.yaml,那么在使用jsonpath的时候需要对key中的点.进行转义。

1
kubectl get cm test-config -n test -o jsonpath='{.data.config\.yaml}'
  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-jsonpath-start/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~