4

我怎样才能在shell中做字典结构?我的目标是生成随机单词。前任。肮脏的鱼,好书,丑陋的钢琴或pesante意大利面,giallo cane ...它的js代码看起来像这样

    words ={

"italian" :
{
    "name" :
            [
             "gatto", 
             "cane", 
             "pasta", 
             "telefono", 
             "libro"
             ],

    "adjective" : 
            [
             "pesante", 
             "sottile", 
             "giallo", 
             "stretto",      
             ]
},
"english" :
{
    "name" : 
            [
             "fish", 
             "book",
             "guitar",
             "piano",
             ],     
    "adjective" :
            [
              "dirty",
              "good",
              "ugly",
              "great",   
             ]
}}

我要这个:

words[english][adjective][1]
>> good
4

1 回答 1

21

本身不能存储复杂的数据结构,但与大多数情况下在 shell 中一样,您可以使用外部工具,我在这里演示了 6 种不同的解决方案,都在 Unix* 中,如 shell :

首先,你JSON的坏了,这是一个有效的版本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

输出:

good

使用jqRANDOMshell 变量:

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

jq,看教程

使用

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

输出:

...
good

使用

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

输出 :

good

使用

让我们在 perl 命令行中解析 DS:

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

输出:

good

使用

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

输出:

good

使用

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

输出:

good
于 2014-11-25T13:08:01.650 回答