2
2

More than 1 year has passed since last update.

#jq コマンドで #json 配列をスライスする例

Last updated at Posted at 2019-04-20

n番目の要素

  • 0が1番目
  • 1が2番目
  • 2が3番目

多くのプログラミングの悪癖を引き継いでいるよね‥?

$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0]'
1
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[1]'
2
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[2]'
3

n番目以降の要素

コロンで区切り、後ろを空にする ( [0:] など )

$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0:]'
[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[2:]'
[
  3,
  4,
  5,
  6,
  7,
  8,
  9
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[4:]'
[
  5,
  6,
  7,
  8,
  9
]

n番目からm番目の要素

  • 0:0 ‥これ動かないんだよね
  • 0:1 で 1番目の要素が取れる
  • 0:2 で 1番目-2番目の要素が取れる‥ふざんけんなよ
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0:0]'
[]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0:1]'
[
  1
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0:2]'
[
  1,
  2
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[0:3]'
[
  1,
  2,
  3
]

jq 1.5 Manual

始端は含まれ、終端は含まれると‥うう‥ふざけるなよ‥

The .[10:15] syntax can be used to return a subarray of an array or substring of a string. The array returned by .[10:15] will be of length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive). Either index may be negative (in which case it counts backwards from the end of the array), or omitted (in which case it refers to the start or end of the array).

n番目の要素 (うしろから数えて)

$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-1]'
9
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-2]'
8
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-3]'
7

n番目からm番目の要素 (うしろから数えて)

なんとも融通が効かない感じ。

$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-1:-3]'
[]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-3:-1]'
[
  7,
  8
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-3:]'
[
  7,
  8,
  9
]
$ echo "[1,2,3,4,5,6,7,8,9]" | jq '.[-4:]'
[
  6,
  7,
  8,
  9
]

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
2
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
2
2