0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JMESPathのcontainsを使ってincludesとかin_array的なことをする

Last updated at Posted at 2023-09-20

:warning: この文章はGPT-4により生成されています

JMESPathは、JSONドキュメントを照会するための言語である。この言語を用いれば、大きなJSONデータから特定の情報を取り出したり、データの変換を行ったりすることができる。今回のテーマは、JMESPathの contains 関数を活用して、JSONの配列に特定の値が含まれているかどうかの判定方法である。

containsの基本的な使用方法

JMESPathの contains は、ある配列に指定した値が含まれているかどうかを調べる関数である。基本的な使用方法は以下の通り。

contains([検索対象の配列], 探す値)

この関数は、検索対象の配列に探す値が含まれている場合に true を、含まれていない場合に falseを返す。

containsの応用的な使用方法

JMESPathの contains 関数は、第1引数にリテラル配列を指定し、第2引数に変数を指定することで、その変数がリテラル配列内のいずれかの要素と一致するかどうかを確認することができる。例として、以下のJSONデータを考える。

{ "targetNames": ["Alice", "Bob", "Charlie", "David"] }

このデータに対して targetNames に含まれる全ての名前が ["Alice", "Bob", "Charlie"] という配列に含まれているかどうかを確認する照会を行う。

map(&contains(["Alice", "Bob", "Charlie"], @), targetNames)

この照会は targetNames 内の各名前が ["Alice", "Bob", "Charlie"] に含まれているかどうかを確認し、その結果の配列を返す。結果は [true, true, true, false] となる。

AWS CLIでのcontains関数の使用

AWS CLIの--queryオプションを使用して、特定のJSONデータの要素を絞り込む際に、JMESPathの contains 関数は非常に有効である。例えば、AWS Step Functionsの実行履歴から特定のIDのイベントだけを取得したい場面を考える。以下のコマンドを実行することで、IDが1, 3, 5, 7, 9のいずれかであるイベントだけを絞り込んで取得することができる。

aws stepfunctions get-execution-history \
--execution-arn arn:aws:states:ap-northeast-1:000000000000:execution:xxx:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx \
--query 'events[?contains([`1`,`3`,`5`,`7`,`9`],id)]'

このように、JMESPathの contains 関数を活用することで、JSONデータの照会や変換、そしてAWS CLIでのデータの絞り込みが非常に効率的に行えるのである。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?