Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON with jq

Tags:

json

jq

I am trying to create a JSON file with jq from the result of the command "lsb_release"

What i have done :

if [ -x "$(command -v lsb_release)" ]; then
    lsb_release -a  | jq  --raw-input 'split("\t") | { (.[0]) : .[1] }' > ubuntu_release.json
fi

the result is

{
  "Distributor ID:": "Ubuntu"
}

{
  "Description:": "Ubuntu 20.04.3 LTS"
}

{
  "Release:": "20.04"
}

{
  "Codename:": "focal"
}

but i want the result

[
    {
      "Distributor ID:": "Ubuntu"
    },
    {
      "Description:": "Ubuntu 20.04.3 LTS"
    },
    {
      "Release:": "20.04"
    },
    {
      "Codename:": "focal"
    }
]

can anybody body help me ? :)

like image 698
Valentin Leblanc Avatar asked Dec 29 '25 13:12

Valentin Leblanc


1 Answers

Usually, when we want to create an array from a stream of inputs, we can use --slurp/-s. But when combined with --raw-input/-R, this causes the entire input to be provided as a single string (that contains line feeds).

Slurping can also be achieved using --null-input/-n and [ inputs | ... ]. And this works as desired for text files.

jq -nR '[ inputs | split("\t") | { (.[0]) : .[1] } ]'

Demo on jqplay


That said, I suspect you will find the following output format more useful:

{
  "Distributor ID": "Ubuntu",
  "Description": "Ubuntu 20.04.3 LTS",
  "Release": "20.04",
  "Codename": "focal"
}

This can be achieved by simply adding | add.

jq -nR '[ inputs | split(":\t") | { (.[0]) : .[1] } ] | add'

Demo on jqplay

One can also use reduce.

jq -nR 'reduce ( inputs | split(":\t") ) as [ $k, $v ] ( {}; . + { ($k): $v } )'

Demo on jqplay

like image 142
ikegami Avatar answered Jan 01 '26 04:01

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!