JSON And The Command Line

Liste des GroupesRevenir à cu shell 
Sujet : JSON And The Command Line
De : ldo (at) *nospam* nz.invalid (Lawrence D'Oliveiro)
Groupes : comp.unix.shell
Date : 11. Aug 2024, 05:50:44
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v99fv3$33qsp$1@dont-email.me>
User-Agent : Pan/0.159 (Vovchansk; )
Quite a few Linux utilities have the option to format their output as
JSON, for easy subsequent processing with commands like jq
<https://manpages.debian.org/1/jq.1.en.html>.

For example, here’s what part of the output from “lscpu -J” looks like
on one of my machines:

    {
       "lscpu": [
          {
             "field": "Architecture:",
             "data": "x86_64"
          },{
             "field": "CPU op-mode(s):",
             "data": "32-bit, 64-bit"
          },{
             "field": "Address sizes:",
             "data": "36 bits physical, 48 bits virtual"
          },{
             "field": "Byte Order:",
             "data": "Little Endian"
          },{
             "field": "CPU(s):",
             "data": "8"
          },{
        ...
    }

That’s a bit verbose, isn’t it? jq can still select information from
here, but wouldn’t it look a bit neater if instead of

    {
        "field": «key»,
        "data": «value»
    }

you had the more concise

    {«key»: «value»}

?

Actually it’s quite easy to do this transformation. jq has built-in
functions “to_entries” and “from_entries” which can convert between
the verbose and concise layouts, but it only recognizes names like
“key” and “value”, not “field” and “data”.

Never mind: it’s easy enough to remap the names. Putting it all
together, including pulling out the lone “lscpu” field from the
original struct, here is the JSON processing pipeline:

    lscpu -J | jq '.lscpu | map({"key" : .field, "value" : .data}) | from_entries'

And the initial part of the corresponding output:

    {
      "Architecture:": "x86_64",
      "CPU op-mode(s):": "32-bit, 64-bit",
      "Address sizes:": "36 bits physical, 48 bits virtual",
      "Byte Order:": "Little Endian",
      "CPU(s):": "8",
      ...
    }

Date Sujet#  Auteur
11 Aug 24 o JSON And The Command Line1Lawrence D'Oliveiro

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal