skip to Main Content

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 second? 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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can use

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

    Demo

    in order to get key-value pairs without quotes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search