Home > other >  jq convert to csv with keys to column rows
jq convert to csv with keys to column rows

Time:02-10

I have json, example like this

{
    "server1": {
        "dhcp-libs": "12:4.2.5-83.el7.centos.1",
        "perl-Time-Local": "1.2300-2.el7",
        "kbd-legacy": "1.15.5-15.el7",
        "perl-Scalar-List-Utils": "1.27-248.el7",
        "ncurses-base": "5.9-14.20130511.el7_4",
        "firewalld": "0.6.3-13.el7_9",
        "perl-threads": "1.87-4.el7",
        "aic94xx-firmware": "30-6.el7",
        "kpartx": "0.4.9-135.el7_9",
        "perl-Getopt-Long": "2.40-3.el7",
        "basesystem": "10.0-7.el7.centos",
        "rsyslog": "8.24.0-57.el7_9.1",
        "libtirpc": "0.2.4-0.16.el7",
        "python3-libs": "3.6.8-18.el7",
        "btrfs-progs": "4.9.1-1.el7",
        "ncurses-libs": "5.9-14.20130511.el7_4",
        "python36-m2crypto": "0.35.2-5.el7"
    }
}
{
    "server2": {
        "perl-Errno": "1.28-420.el8",
        "fontpackages-filesystem": "1.44-22.el8",
        "python3-hawkey": "0.63.0-3.el8",
        "geolite2-city": "20180605-1.el8",
        "bind-libs-lite": "32:9.11.26-6.el8",
        "samba-client-libs": "4.14.5-2.el8",
        "rdma-core": "35.0-1.el8",
        "iptables": "1.8.4-20.el8",
        "python3-firewall": "0.9.3-7.el8",
        "policycoreutils-python-utils": "2.9-16.el8",
        "lvm2-libs": "8:2.03.12-10.el8",
        "rpm-plugin-selinux": "4.14.3-19.el8"
    }
}

Is it possible convert JSON usinq jq to CSV in format where keys are first row and values senocd? Result should be like this

dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
ncurses-base,5.9-14.20130511.el7_4
....

Is that possible or should I try something else?

CodePudding user response:

This generates your desired output (keys as first, rows as second column), formatted as CSV with escaping of delimiters used in the data and quotes around the fields:

jq -r '.[] | to_entries[] | [.[]] | @csv'
"dhcp-libs","12:4.2.5-83.el7.centos.1"
"perl-Time-Local","1.2300-2.el7"
"kbd-legacy","1.15.5-15.el7"
"perl-Scalar-List-Utils","1.27-248.el7"
...

Demo

If you don't want the quotes, you could use join(",") instead of @csv but this wouldn't do any escaping either:

jq -r '.[] | to_entries[] | [.[]] | join(",")'
dhcp-libs,12:4.2.5-83.el7.centos.1
perl-Time-Local,1.2300-2.el7
kbd-legacy,1.15.5-15.el7
perl-Scalar-List-Utils,1.27-248.el7
...

Demo

CodePudding user response:

You can use

jq -r '.[] | to_entries[] | [ .key, .value ] | join(",")'

Demo

in order to get key-value pairs without quotes

  • Related