加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在shell中解析JSON

发布时间:2020-12-15 18:58:38 所属栏目:安全 来源:网络整理
导读:我怎么能在shell中做字典结构?我的目标是生成随机单词.防爆.脏鱼,好书,丑陋的钢琴或pesante面食,giallo甘蔗……它的js代码看起来像这样 words ={"italian" :{ "name" : [ "gatto","cane","pasta","telefono","libro" ],"adjective" : [ "pesante","sottile"
我怎么能在shell中做字典结构?我的目标是生成随机单词.防爆.脏鱼,好书,丑陋的钢琴或pesante面食,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",]
}}

我要这个:

words[english][adjective][1]
>> good
shell本身不能存储复杂的数据结构,但是像shell中的大部分时间一样,你可以使用外部工具,我在这里演示了6种不同的解决方案,所有这些都在Unix *中像shell一样:

首先,您的JSON已损坏,这是file.js中的有效版本:

{
   "italian" : {
      "name" : [
         "gatto","libro"
      ],"adjective" : [
         "pesante","stretto"
      ]
   },"english" : {
      "name" : [
         "fish","piano"
      ],"adjective" : [
         "dirty","great"
      ]
   }
}

使用jq

$jq '.english.adjective[1]' file.js

输出:

good

使用jq和RANDOM shell变量:

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

jq,见tutorial.

使用rhino

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

输出:

...
good

使用node.js

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

输出:

good

使用perl

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

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

输出:

good

使用python

$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

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

输出:

good

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读