[英]Parse JSON in shell
我如何在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
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
玩jq
和RANDOM
shell变量:
$ 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
输出:
...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.