🖥

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
]
``````