bash 在 shell 中解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27127091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JSON in shell
提问by angela
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
我如何在shell中做字典结构?我的目标是生成随机单词。前任。脏鱼、好书、丑陋的钢琴或意大利面、giallo 手杖……它的 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",
]
}}
I want this:
我要这个:
words[english][adjective][1]
>> good
回答by Gilles Quenot
The shellitself 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:
该壳本身不能存储复杂的数据结构,但最喜欢的外壳时,您可以使用外部工具,我在这里表现出6个不同的解决方案,所有在Unix中*炮弹一样:
First, your JSON
is broken, this is a valid version in file.js
:
首先,你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"
]
}
}
Using jq
使用jq
$ jq '.english.adjective[1]' file.js
Output:
输出:
good
Playing with jq
and RANDOM
shell variable :
使用jq
和RANDOM
shell 变量:
$ echo $(
jq ".english.adjective[$((RANDOM%4))], .english.name[$((RANDOM%4))]" file.js
)
"great" "piano"
Using rhino
使用犀牛
$ rhino<<EOF 2>/dev/null
hash = $(<file.js)
print(hash.english.adjective[1])
EOF
Output:
输出:
...
good
Using node.js
使用node.js
$ node<<EOF
hash = $(<file.js)
console.log(hash.english.adjective[1])
EOF
Output :
输出 :
good
Using perl
使用perl
Let's parse the DS in a perl command line :
让我们在 perl 命令行中解析 DS:
$ perl -MJSON -0lnE '
$words = decode_json $_;
say $words->{english}->{adjective}->[1]
' file.js
Output:
输出:
good
Using python
使用蟒蛇
$ 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
使用红宝石
$ ruby<<EOF
require 'json'
file = File.read('file.js')
data = JSON.parse(file)
print(data['english']['adjective'][1])
EOF
Output:
输出:
good