Parse JSON in shell

11,855

The itself can't store complicated Data Structures, but like most of the time in shell, you can use external tools, I demonstrate here 6 different solutions, all in Unix* like shells:

First, your JSON is broken, this is a valid version in file.js :

{
   "italian" : {
      "name" : [
         "gatto",
         "cane",
         "pasta",
         "telefono",
         "libro"
      ],
      "adjective" : [
         "pesante",
         "sottile",
         "giallo",
         "stretto"
      ]
   },
   "english" : {
      "name" : [
         "fish",
         "book",
         "guitar",
         "piano"
      ],
      "adjective" : [
         "dirty",
         "good",
         "ugly",
         "great"
      ]
   }
}

Using

$ jq '.english.adjective[1]' file.js

Output:

good

Playing with jq and RANDOM shell variable :

$ echo $(
    jq ".english.adjective[$((RANDOM%4))], .english.name[$((RANDOM%4))]" file.js
)
"great" "piano"

jq, see the tutorial.

Using

$ rhino<<EOF 2>/dev/null
hash = $(<file.js)
print(hash.english.adjective[1])
EOF

Output:

...
good

Using

$ node<<EOF
hash = $(<file.js)
console.log(hash.english.adjective[1])
EOF

Output :

good

Using

Let's parse the DS in a perl command line :

$ perl -MJSON -0lnE '
    $words = decode_json $_;
    say $words->{english}->{adjective}->[1]
' file.js

Output:

good

Using

$ python<<EOF
import json
json_data = open('file.js')
data = json.load(json_data)
json_data.close()
print(data['english']['adjective'][1])
EOF

Output:

good

Using

$ ruby<<EOF
require 'json'
file = File.read('file.js')
data = JSON.parse(file)
print(data['english']['adjective'][1])
EOF

Output:

good
Share:
11,855
angela
Author by

angela

Updated on June 06, 2022

Comments

  • angela
    angela almost 2 years

    How can i do dictionary structure in shell? My aim is to generate random words. Ex. dirty fish, good book, ugly piano or pesante pasta, giallo cane... Its js code look like this

        words ={
    
    "italian" :
    {
        "name" :
                [
                 "gatto", 
                 "cane", 
                 "pasta", 
                 "telefono", 
                 "libro"
                 ],
    
        "adjective" : 
                [
                 "pesante", 
                 "sottile", 
                 "giallo", 
                 "stretto",      
                 ]
    },
    "english" :
    {
        "name" : 
                [
                 "fish", 
                 "book",
                 "guitar",
                 "piano",
                 ],     
        "adjective" :
                [
                  "dirty",
                  "good",
                  "ugly",
                  "great",   
                 ]
    }}
    

    I want this:

    words[english][adjective][1]
    >> good
    
  • suryakrupa
    suryakrupa over 8 years
    jq was a perfect solution!