I have created a csv output from an input JSON file.
我从输入JSON文件创建了一个csv输出。
Since some JSON arrays do not have their own id's, I need to add a unique id in my csv output that will be based on index of current element in its JSON array.
由于一些JSON数组没有自己的id,我需要在我的csv输出中添加一个唯一的id,它将基于其JSON数组中当前元素的索引。
Is there any built-in JQ function returning the element index?
是否有任何内置的JQ函数返回元素索引?
3 个解决方案
#1
3
to_entries
should work perfectly.
to_entries应该完美。
jq -n '["a","b","c"] | to_entries'
will produce
会产生
[{"key":0,"value":"a"},{"key":1,"value":"b"},{"key":2,"value":"c"}]
#2
2
There are two robust (i.e., that work in jq 1.3, 1.4 and 1.5) ways to iterate through an array with an index: one is to use keys[] (which works on arrays as well as objects), and the other using range/2. These two approaches can be illustrated as follows, assuming $a is an array:
有两个健壮的(即,在jq 1.3,1.4和1.5中工作)方法迭代一个带索引的数组:一个是使用keys [](它对数组和对象起作用),另一个使用范围/ 2。假设$ a是一个数组,这两种方法可以说明如下:
($a | keys[]) as $i | [$i, $a[$i]]
range(0; $a | length) as $i | [$i, $a[$i]]
Or more succinctly:
或者更简洁:
$a | keys[] as $i | [$i, .[$i]]
$a | range(0;length) as $i | [$i, .[$i]]
(index/1 is probably not what is needed here.)
(index / 1可能不是这里需要的。)
#3
#1
3
to_entries
should work perfectly.
to_entries应该完美。
jq -n '["a","b","c"] | to_entries'
will produce
会产生
[{"key":0,"value":"a"},{"key":1,"value":"b"},{"key":2,"value":"c"}]
#2
2
There are two robust (i.e., that work in jq 1.3, 1.4 and 1.5) ways to iterate through an array with an index: one is to use keys[] (which works on arrays as well as objects), and the other using range/2. These two approaches can be illustrated as follows, assuming $a is an array:
有两个健壮的(即,在jq 1.3,1.4和1.5中工作)方法迭代一个带索引的数组:一个是使用keys [](它对数组和对象起作用),另一个使用范围/ 2。假设$ a是一个数组,这两种方法可以说明如下:
($a | keys[]) as $i | [$i, $a[$i]]
range(0; $a | length) as $i | [$i, $a[$i]]
Or more succinctly:
或者更简洁:
$a | keys[] as $i | [$i, .[$i]]
$a | range(0;length) as $i | [$i, .[$i]]
(index/1 is probably not what is needed here.)
(index / 1可能不是这里需要的。)