【问题标题】:Export json via jq to csv通过 jq 导出 json 到 csv
【发布时间】:2021-03-30 14:13:08
【问题描述】:

我将此输出为 test.json(它是 AWS 提取,但我已更改名称)

[
    {
        "InstanceId": "I-1234",
        "Vol": "vol-5678",
        "Delete": false,
        "State": "in-use",
        "Tags": [
            {
                "Key": "Size",
                "Value": "large"
            },
            {
                "Key": "Colour",
                "Value": "red"
            },
            {
                "Key": "Shape",
                "Value": "square"
            },
            {
                "Key": "Weight",
                "Value": "light"
            }
        ]
    }
]

我想导出特定字段,包括所有标签到 csv,所以它看起来像这样:

id,vol,state,size,colour,shape,weight
value,value,value,value,value,value,value

我已经运行了这个:

猫测试.json | jq -c ' { id: .[].InstanceId, vol: .[].Vol, 标签: .[].Tags |映射([.Key,.Value] | 加入(“:”))| @csv } ' >> test.csv

它看起来像这样:

cat test.csv
{"id":"I-1234","vol":"vol-5678","tags":"\"Size:large\",\"Colour:red\",\"Shape:square\",\"Weight:25kg\""}

如果我在 Excel 中打开,看起来像:

{"id":"I-1234"  vol:"vol-5678"  tags:"\"Size:large\"    \"Colour:red\"  \"Shape:square\"    \"Weight:25kg\""}

我将在许多 aws 资源上循环,并希望继续附加到 csv。

I want to remove 
{ } at beginning and end.

the key description I would like at top as a header, rather than to the left of the value..

    so for: "id":"I-1234"   vol:"vol-5678"
    I would like
    id, vol
    I-1234, vol-5678

and the same with the Tags
remove the Array Name: "tags:" ( think its the array name, I'm not a developer, infrastructure dude! ) and just leave
Size,Colour,Shape,Weight, ...
large,red,square,25kg, ...

Can anyone help, point me in the right direction ..
thanks .. :)

【问题讨论】:

    标签: json csv export-to-csv jq


    【解决方案1】:
    jq -r '
      ["Size","Colour","Shape","Weight"] as $Keys
      | (["id", "vol"] + ($Keys|map(ascii_downcase))),
        ( .[]
         | (.Tags|from_entries) as $dict
         | [.InstanceId, .Vol, $dict[$Keys[]]] )
      | @csv
    '
    

    这将生成有效的 CSV,列按所需顺序排列,而与 .Tags 数组中项目的顺序无关。

    如果您不想引用行中的字符串,那么(冒着没有有效 CSV 的风险)可以考虑的一种选择是将上面的 @csv 替换为 join(",")。或者,您可能希望考虑使用@tsv,然后用逗号替换制表符(例如,使用sedtr 甚至jq :-)。

    【讨论】:

    • 我知道我不应该,但上帝那太好了,谢谢.. 我花了 3 天时间把头发拔掉。我永远不会这样做。就像您以相反的顺序开始,然后从更深的 Json 备份..
    猜你喜欢
    • 2020-09-23
    • 2019-04-26
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2022-01-23
    • 2015-01-07
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多