기타

[JMESPath] Projections

비번변경 2022. 9. 27. 21:14

Projections

JMESPath의 주요 기능 중 하나로, 요소의 집합에 식을 적용할 수 있게 한다. Projections 종류는 5가지로 나눌 수 있다. 

  • List Projections
  • Slice Projections
  • Object Projections
  • Flatten Projections
  • Filter Projections

2022.09.27 - [JMESPath] Projections에 이어서 살펴보도록 하자.

 

List and Slice Projections

List Projections은 와일드카드 표현식에 의해 만들어진 JSON 배열에 적용된다.

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

위의 JSON 데이터에서 people.first에 해당하는 값만 출력하려고 한다. 이 경우에는 people[*]로 first, last로 구성된 JSON 배열로 접근한 뒤,

# people[*]
[
  {
    "first": "James",
    "last": "d"
  },
  {
    "first": "Jacob",
    "last": "e"
  },
  {
    "first": "Jayden",
    "last": "f"
  },
  {
    "missing": "different"
  }
]

각 배열의 first 식별자를 취하면 된다.

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

 

슬라이싱을 적용하면 다음과 같다.

# people[:2].first
[
  "James",
  "Jacob"
]

 

 

Object Projections

Object Projections은 JSON 객체에 정의된다.

# JSON
{
  "ops": {
    "functionA": {"numArgs": 2},
    "functionB": {"numArgs": 3},
    "functionC": {"variadic": true}
  }
}

위의 JSON 데이터에서 ops 아래 모든 function의 numArgs 값을 출력하려고 한다. 이 경우에는 먼저 ops.*로 접근하여 다음과 같은 JSON 배열을 얻을 수 있다.

# ops.*
[
  {
    "numArgs": 2
  },
  {
    "numArgs": 3
  },
  {
    "variadic": true
  }
]

각 배열의 numArgs 값만 취하면 된다.

# ops.*.numArgs
[
  2,
  3
]

 

 

Flatten Projections

List, Object Projections의 결과는 원본 JSON 데이터 구조를 유지하는데, 이 구조를 한 단계 평면화할 때 사용한다.

# JSON
{
  "reservations": [
    {
      "instances": [
        {"state": "running"},
        {"state": "stopped"}
      ]
    },
    {
      "instances": [
        {"state": "terminated"},
        {"state": "running"}
      ]
    }
  ]
}

위의 JSON 데이터에서 List Projection을 이용해 state 값만 출력하는 표현식과 그 결과는 아래와 같다.

# reservations[*].instances[*].state
[
  [
    "running",
    "stopped"
  ],
  [
    "terminated",
    "running"
  ]
]

깊이가 2인 배열이 결과로 나오는데, 이를 깊이가 1인 배열로 바꾸고 싶다면 [*] 대신 []를 사용하면 된다.

# reservations[*].instances[].state
[
  "running",
  "stopped",
  "terminated",
  "running"
]

 

 

Filter Projections

Filter Projections을 사용하면 원하는 키와 값으로 조건을 주어 데이터를 필터링할 수 있다. 필터링 시에는 [?key comparator value] 형식으로 작성한다.

# JSON
{
  "machines": [
    {"name": "a", "state": "running"},
    {"name": "b", "state": "stopped"},
    {"name": "b", "state": "running"}
  ]
}

예로 들어 위의 machines 데이터에서 state가 running인 객체의 name 값을 출력하고자 한다. 이 경우에는 [?state=='running']이 필터 조건이 된다.

# machines[?state=='running'].name
[
  "a",
  "b"
]

조건 연산자는 ==, !=, <, <=, >, >=가 올 수 있다.

 

 

 

참고 문서

https://jmespath.org/tutorial.html

 

 

 

728x90