简体   繁体   English

如何使用 JQ 将 JSON 数组值展平为 CSV

[英]How to flatten JSON array values as CSV using JQ

I have a JSON file containing application clients and their associated application features:我有一个 JSON 文件,其中包含应用程序客户端及其相关的应用程序功能:

{
    "client-A": [
        "feature-x"
    ],
    "client-B": [
        "feature-x",
        "feature-y"
    ],
    "client-C": [
        "feature-z"
    ],
    "client-D": [
        "feature-x",
        "feature-z"
    ],
    ...
}

I'm trying to turn this into the following CSV:我试图把它变成下面的 CSV:

client,feature
client-A,feature-x
client-B,feature-x
client-B,feature-y
client-C,feature-z
client-D,feature-x
client-D,feature-z

What's an easy way using jq to get this done?使用jq完成这项工作的简单方法是什么?

Not sure whether this is the most efficient way of doing it, but you can convert use the following pipeline:不确定这是否是最有效的方法,但您可以使用以下管道进行转换:

<yourfile.json jq -r 'to_entries | .[] | { key: .key, value: .value[] } | [ .key, .value ] | @csv'

to_entries converts the structure into "key value" pairs, which can then be operated on. to_entries将结构转换为“键值”对,然后可以对其进行操作。 The { key: .key, value: .value[] } bit will convert the array into multiple rows... { key: .key, value: .value[] }位会将数组转换为多行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM