我有以下类型的json:
{
"foo": "hello",
"bar": [
{
"key": "k1",
"val": "v1"
},
{
"key": "k2",
"val": "v2"
},
{
"key": "k3",
"val": "v3"
}
]
}
我想输出以下内容:
"hello", 1, "k1", "v1"
"hello", 2, "k2", "v2"
"hello", 3, "k3", "v3"
我正在使用jq转换它,答案也应该是jq转换。
我目前在:
echo '{"foo": "hello","bar": [{"key": "k1","val": "v1"},{"key": "k2","val": "v2"},{"key": "k3","val": "v3"} ]}' | jq -c -r '.bar[] as $b | [.foo, ($b | .key, .val)] | @csv'
这给了我:
"hello","k1","v1"
"hello","k2","v2"
"hello","k3","v3"
如何获取索引以显示正在解析的数组元素?
答案 0 :(得分:8)
您可以将数组转换为条目以访问索引和值。然后,您可以构建CSV行。
$ jq -r '[.foo] + (.bar | to_entries[] | [.key+1,.value.key,.value.val]) | @csv' input.json
"hello",1,"k1","v1"
"hello",2,"k2","v2"
"hello",3,"k3","v3"
答案 1 :(得分:2)
假设您可以访问jq 1.5并且键/ val键按顺序显示:
jq -r '.foo as $foo
| foreach .bar[] as $i (0; .+1; [$foo, .] + [$i[]])
| @csv'
会产生:
"hello",1,"k1","v1"
"hello",2,"k2","v2"
"hello",3,"k3","v3"
-c选项通常与@csv一起使用,将@csv生成的JSON字符串转换为以逗号分隔的值列表。
如果您真的想加入",",那么它有点麻烦,但如果您不担心@csv提供的功能,请在此处'一种方式:
$ jq -r '"\"\(.foo)\"" as $foo
| foreach .bar[] as $i
(0; .+1; "\($foo), \(.), \($i | map("\"\(.)\"")|join(", "))")'
这会产生:
"hello", 1, "k1", "v1"
"hello", 2, "k2", "v2"
"hello", 3, "k3", "v3"
如果您的jq没有foreach
,那么您可以同样使用reduce
,但升级可能会更容易。