Home > Mobile >  JSON selector for jq
JSON selector for jq

Time:07-16

I would like to get a CSV file from the Mozilla CommonVoice JSON statistics. It looks like this:

{
  ...,
  "locales": {
    "en": {
      ...,
      "validHrs": 2275.28
    },
    "fa": {
      ...,
      "validHrs": 327.14
    },
  }
}

I manage to get the value of validHrs for a single language:

jq ".locales.en.validHrs" cv-corpus-10.0-2022-07-04.json
2275.28
jq ".locales.fa.validHrs" cv-corpus-10.0-2022-07-04.json
327.14

But not for all. Goal is a CSV with:

en,2275.28
fa,327.14
...

CodePudding user response:

This works for me:

cat cv-corpus-10.0-2022-07-04.json| jq -r '.locales | keys[] as $k | "\($k),\(.[$k] | .validHrs)"'

The output looks like:

ab,59.71
ar,87.747
as,2.14
ast,0
az,0.12
ba,256.46
bas,2.04
be,1089.38
bg,9.15
bn,61.6
br,9.56
ca,1389.83
...

CodePudding user response:

You can use to_entries which will give you each key, value pair:

$ jq -r '.locales | to_entries[] | "\(.key),\(.value.validHrs)"' cv.json 
en,2275.28
fa,327.14
fr,868.35
es,411.31
sl,10.09
kab,552.81
[...]
  • Related