简体   繁体   中英

How to flatten JSON array values as CSV using JQ

I have a JSON file containing application clients and their associated application features:

{
    "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:

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?

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. The { key: .key, value: .value[] } bit will convert the array into multiple rows...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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