Search code examples
jsonexport-to-csvjq

use jq to format json data into csv data


{
    "Users": [
        {
            "Attributes": [
                {
                    "Name": "sub",
                    "Value": "1"
                },
                {
                    "Name": "phone_number",
                    "Value": "1234"
                },
                {
                    "Name": "referral_code",
                    "Value": "abc"
                }
            ]
        },
        {
            "Attributes": [
                {
                    "Name": "sub",
                    "Value": "2"
                },
                {
                    "Name": "phone_number",
                    "Value": "5678"
                },
                {
                    "Name": "referral_code",
                    "Value": "def"
                }
            ]
        }
    ]
}

How can I produce output like below ?

1,1234,abc

2,5678,def

jq '.Users[] .Attributes[] .Value' test.json

produces


1
1234
abc
2
5678
def

Solution

  • Not sure this is the cleanest way to handle this, but the following will get the desired output:

    .Users[].Attributes | map(.Value) | @csv
    
    1. Loop through all the deep Attributes .Users[].Attributes
    2. map() to get all the Value's
    3. Convert to @csv

    jqPlay demo