JQ 平面对象转 csv

JQ 平面对象转 csv

我需要展平这个扁平对象的 json 数组

[{
  "key1a": "value1",
  "key1b": "value2",
  ...
  "key1z": "value50",
},
{
  "key2a": "value2a",
  "key2b": "value2b",
  ...
  "key2y": "value2y",
},
{...},{...}]

到这个 csv 样式的输出

key1a+key1b+key1c... value1a|value1b|value1c...
key2a+key2b+key2c... value2a|value2b|value2c...

为了用 进行一些后处理awk

我尝试使用ja函数 map、add 和 flatten 但没有成功。

答案1

由于预期输出不是 CSV,因此我不会使用;@csv中找到的运算符。jq相反,我只会天真地插入问题中提到的分隔符。如果输入中的任何键或值包含+|或空格,则需要在一些额外的处理步骤中对它们进行适当的转义。

+可以使用以下jq表达式将键连接在一起作为分隔符:

.[] | keys | join("+")

|可以使用以下jq表达式将这些值连接在一起作为分隔符:

.[] | [.[]] | join("|")

使用空格作为分隔符连接每个数组元素的两个键值字符串:

.[] |
[
    ( keys  | join("+") ),
    ( [.[]] | join("|") )
] |
join(" ")

测试这个:

$ cat file.json
[
  {
    "key1a": "value1a",
    "key1b": "value2a",
    "key1z": "value50"
  },
  {
    "key2a": "value2a",
    "key2b": "value2b",
    "key2y": "value2y"
  }
]
$ jq -r '.[] | [ (keys | join("+")), ([.[]] | join("|")) ] | join(" ")' file.json
key1a+key1b+key1z value1a|value2a|value50
key2a+key2b+key2y value2a|value2b|value2y

答案2

这对你有用吗?

$ cat input.json | jq -r '.[] | to_entries | ([ .[].key ] | join("+")) + " " + ([ .[].value ] | join("|"))'
key1a+key1b+key1z value1a|value2a|value50
key2a+key2b+key2y value2a|value2b|value2y
$ cat input.json
[{
  "key1a": "value1a",
  "key1b": "value2a",
  "key1z": "value50"
},
{
  "key2a": "value2a",
  "key2b": "value2b",
  "key2y": "value2y"
}]

相关内容