Reputation: 103
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
Upvotes: 5
Views: 18232
Reputation: 177
source <(curl -s -L -o- https://github.com/lirik90/bashJsonParser/raw/master/jsonParser.sh)
JSON=$(minifyJson "$JSON")
echo "Result is: $(parseJson "$JSON" english adjective 1)"
Output:
Result is: good
Upvotes: 1
Reputation: 185640
The shell 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"
]
}
}
$ 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"
$ rhino<<EOF 2>/dev/null
hash = $(<file.js)
print(hash.english.adjective[1])
EOF
Output:
...
good
$ node<<EOF
hash = $(<file.js)
console.log(hash.english.adjective[1])
EOF
Output :
good
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
$ 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
$ ruby<<EOF
require 'json'
file = File.read('file.js')
data = JSON.parse(file)
print(data['english']['adjective'][1])
EOF
Output:
good
Upvotes: 24