在 shell 中解析 JSON

5

如何在shell中创建字典结构?我的目标是生成随机单词,例如:dirty fish, good book, ugly piano 或者 pesante pasta, 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

8
针对此问题,Shell并不是正确的编程语言。虽然一些Shell支持关联数组,但很少或者没有支持将一个数组嵌套到另一个数组中。 - chepner
看我的回答,jq 是一个 shell 工具,可以轻松解析 JSON。 - Gilles Quénot
2个回答

24

本身无法存储复杂的数据结构,但像大多数情况下一样,您可以使用外部工具。我在这里演示了六种不同的解决方案,均在类 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

使用 jqRANDOM shell 变量进行玩耍:

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

jq,参见tutorial

使用

$ 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

1

使用纯 3.2+,无需依赖项(如 jq、python、grep 等):

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)"

输出:

Result is: good

试一下吧


请不要发布重复的答案。如果您发现问题足够相似,可以使用相同的答案,请留下评论建议将其关闭为重复。 - tripleee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接