기타

[JMESPath] JSON 쿼리 기본 - 2

비번변경 2022. 9. 28. 20:58

개요

2022.09.26 - [JMESPath] JSON 쿼리 기본 - 1

2022.09.27 - [JMESPath] Projections

에 이어서 남은 문법을 정리해둔다.

 

Pipe Expressions

Projections 결과인 JSON 배열이 아니라 그 배열의 특정 요소만을 원할 때 사용할 수 있다.

# JSON
{
  "people": [
    {"first": "James", "last": "d"},
    {"first": "Jacob", "last": "e"},
    {"first": "Jayden", "last": "f"},
    {"missing": "different"}
  ],
  "foo": {"bar": "baz"}
}

위의 JSON 데이터에서 사람의 이름을 출력하는 표현식과 그 결과는 아래와 같다.

# people[*].first
[
  "James",
  "Jacob",
  "Jayden"
]

 

위 값 중에서 Jacob의 이름만을 원하는 경우 Pipe를 이용하여 값을 추출할 수 있다.

# people[*].first | [1]
"Jacob"

 

 

다중 선택

다중 선택을 이용해 JSON 객체 또는 배열 형태로 결과를 출력할 수 있다.

 

# JSON
{
  "people": [
    {
      "name": "a",
      "state": {"name": "up"}
    },
    {
      "name": "b",
      "state": {"name": "down"}
    },
    {
      "name": "c",
      "state": {"name": "up"}
    }
  ]
}

위의 JSON 데이터에서 people.name과 people.state.name 값을 배열로 출력할 때는 출력할 값을 []로 감싸면 된다.

# people[].[name, state.name]
[
  [
    "a",
    "up"
  ],
  [
    "b",
    "down"
  ],
  [
    "c",
    "up"
  ]
]

people.name과 people.state.name 값을 JSON 객체로 출력할 때는 출력할 값을 {}로 감싸고, 각 값에 key를 정해주어야 한다.

# people[].{Name: name, State: state.name}
[
  {
    "Name": "a",
    "State": "up"
  },
  {
    "Name": "b",
    "State": "down"
  },
  {
    "Name": "c",
    "State": "up"
  }
]

 

 

함수

JMESPath는 max, abs, not_null 등과 같은 함수를 지원한다. 내장 함수 목록은 https://jmespath.org/specification.html#builtin-functions에서 확인할 수 있다.

 

함수를 사용할 때 @ 문자는 현재 요소를 의미한다.

 

 

 

참고 문서

https://jmespath.org/tutorial.html

 

 

728x90