참고
JSON PATH
기본 문법 요소
NOTE
•
$ : 루트 노드 (JSONPath의 모든 표현식은 이걸로 시작된다.)
•
@ : 현재 노드 (아래에서 소개할 조건부 필터 표현식에 사용된다.)
•
. : 하위 노드
•
.. : 중첩된 전체 하위 요소
•
[] : 배열 인덱스
•
* : 모든 요소와 매칭되는 와일드 카드
•
? : 조건부 필터 표현식
{
"bicycle": {
"color": "red",
"price": 19.95
}
}
JSON
복사
객체 다루기
$.bicycle # [{"color": "red", "price": 19.95}]
$.bicycle.color # ["red"]
Bash
복사
하위 노드는 .으로 구분, JSONPath의 결과불은 항상 배열형태로 나온다.
{
"book": [
{
"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
}
]
}
JSON
복사
배열을 다루는 문법
$.book[0:1].isbn # ["0-553-21311-3"], book의 1번째 값의 isbn
$.book[-1:].title # ["The Lord of the Rings"], book의 마지막 값의 타이틀
$.book[*].category # ["fiction", "fiction"], book의 모든 category
Bash
복사
[시작값 : 끝값 +1: 스텝] 형태의 문법.
{
"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
}
}
}
JSON
복사
조건부 필터
# book노드에서 가격이 10 미만인 노드의 제목
# ["Sayings of the Century", "Moby Dick"]
$..book[?(@.price < 10] .title
# store 하위노드에서 카테고리가 reference인 노드의 제목과 작가
# ["Sayings of the Century", "Nigel Rees"]
$.store..[?(@category == 'reference')][title, author]
# store 하위노드에서 색상이 빨강인 노드의 가격
# [19.95]
$.store.[?(@.color == 'red')].price
Bash
복사
조건에 따른 (TRUE, FALSE) 값 출력
echo "cat q9.json | jpath $.employee.payslips[-1:]" > answer9.sh
echo "cat q10.json | jpath $.employee.payslips[-1:].amount" > answer10.sh
echo "cat q12.json | jpath $[0]" > answer12.sh
echo 'cat q13.json | jpath "$[0,3]"' > answer13.sh
Bash
복사
실습코드
쿠버네티스에서의 JSONPath 사용법
NOTE
쿠버네티스는 노드, 리소스 정보를 조회할때 JSONPath 템플릿을 사용할 수 있다!
k get pods -o jsonpath='{JSONPath 문법}'
JSON
복사
{}안에 적어야하며, $는 생략이 가능하다.
# 예시 1
k get nodes -o jsonpath='{.items[*].metadata.name}{"\n"}{.items[*].status.capacity.cpu}'
# 예시 2 (반복목록)
k get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.capacity.cpu}{"\n"}{end}'
# 예시 3 (출력결과 이름)
k get nodes -o custom-columns=Node:.metadata.name,CPU:.status.capacity.cpu
Bash
복사
k get nodes -o json > /opt/outputs/nodes.json
k get node/node01 -o json > /opt/outputs/node01.json
k get nodes -o jsonpath='{.items[*].metadata.name}' > /opt/outputs/node_names.txt
Bash
복사
•
이러한 JSONPath를 활용해서 수천개의 리소스를 쉽게 찾을 수 있다. (SQL 생각)