Shell Json编程

{ "guest_vlan": "1", "g_device": "wifi1", "a_device": "wifi0", "atf_enable": "0", "thermal_analytics": "1", "g_support_mode": "573.5Mbps", "a_support_mode": "1.201Gbps", "athinfo": [ { "radio": "2.4G"...
摘要由CSDN通过智能技术生成

参考:https://www.jianshu.com/p/3898f3b6e8e9

#此文用于shell脚本解析和创建json文件(需要系统内部有支持libubox,同时有/usr/share/libubox/jshn.sh)

Test json file:

 cat test.json 
{
        "name": "Linda",
        "age": "21",
        "address": "Xiamen",
        "hobby": 
        [
                {
                        "sport": "sing",
                        "note": "love you forever"
                },
                {
                        "sport": "basketball",
                        "note": "Kobe"
                }
        ],
        "family": {
                "farther": "Haby",
                "mother": "Lanly",
                "sister": "monily"
        }
}

1. Shell script of parsing json file 

#!/bin/sh

. /lib/functions.sh
# it need system support libubox
. /usr/share/libubox/jshn.sh

#load json file
json_load "`/bin/cat /test.json`"

#directly read name & age
json_get_var name_value name
json_get_var age_value age
echo "****name:$name_value**age:$age_value*******">/dev/console

#output: ****name:Linda**age:21*******

#read array
json_select hobby
# array first index is 1
json_select 1
json_get_var sport_value sport
json_get_var note_value note
echo "******sport:$sport_value**note:$note_value*************"
#output: ******sport:sing**note:love you forever*************

#read all arrays via loop
json_select ..
index=1
while json_get_type status $index && [ "$status" = "object" ];do
json_select $index
json_get_var sport_value sport
json_get_var note_value note
echo "***index:$index***sport:$sport_value**note:$note_value*************"
json_select ..
index=$((index+1))
done
#output:***index:1***sport:sing**note:love you forever*************
#       ***index:2***sport:basketball**note:Kobe*************

#read next json object
#return to first layer object:test.
json_select ..
json_select family
json_get_var farther_value farther
json_get_var mother_value mother
json_get_var sister_value sister
echo "***farther:$farther_value**moterh:$mother_value***sister:$sister_value************"

#output:#output: ******sport:sing**note:love you forever*************


shell script all output:

****name:Linda**age:21*******
******sport:sing**note:love you forever*************
***index:1***sport:sing**note:love you forever*************
***index:2***sport:basketball**note:Kobe*************
***fa

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值