使用jq的json到csv

时间:2017-11-07 21:45:15

标签: json csv jq

希望使用jq将以下json示例转换为csv。这项工作正在以6.9的价格进行,如果需要,我可以在盒子里添加工具。将json规范化为csv的目的是用于SIEM馈送。

JSON:

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  "key4": 4,
  "key5": 5,
  "key6": "value6"
}
{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  "key4": 4,
  "key5": 5,
  "key6": "value6"
}
{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  "key4": 4,
  "key5": 5,
  "key6": "value6"
}

预计输出:

"key1":"Value1","key2":"Value2","key3":"Value3","key4":4,"key5":5,"key6":"Value6"
"key1":"Value1","key2":"Value2","key3":"Value3","key4":4,"key5":5,"key6":"Value6"
"key1":"Value1","key2":"Value2","key3":"Value3","key4":4,"key5":5,"key6":"Value6"

2 个答案:

答案 0 :(得分:0)

首先,那不是csv。引号将被解释为包含单个值。每个逗号分隔值有多组引号。但如果这就是你想要的输出,你绝对可以生成它,只要知道它不是真正的csv。

$ jq -r 'to_entries | map("\(.key|tojson):\(.value|tojson)") | join(",")' input.json

答案 1 :(得分:0)

这是一个生成预期输出的过滤器(假设data.json中的数据):

$ jq -Mr '[keys[] as $k | {($k):.[$k]} | tojson[1:-1]] | join(",")' data.json
"Key1":"Value1","Key2":"Value2","Key3":"Value3","key4":4,"key5":5,"key6":"value6"
"Key1":"Value1","Key2":"Value2","Key3":"Value3","key4":4,"key5":5,"key6":"value6"
"Key1":"Value1","Key2":"Value2","Key3":"Value3","key4":4,"key5":5,"key6":"value6"

Try it online at jqplay.org