15-Openwrt libubox shell上面的应用(JSON解析)

很多情况下我们需要在shell下解析或者组合JSON数据,在libubox里面提供了一个操作json脚本在/usr/share/libubox/jshn.sh文件中。

在libubox编译后的内容中,查找jshn文件,如下:

@ubuntu:~/14.07/build_dir/target-mipsel_1004kc_uClibc-0.9.33.2/libubox-2017-09-29$ find ./ -name "jshn*"
./sh/jshn.sh
./jshn
./ipkg-mtk_1004kc/jshn
./ipkg-mtk_1004kc/jshn/usr/share/libubox/jshn.sh
./ipkg-mtk_1004kc/jshn/usr/bin/jshn
./ipkg-install/usr/share/libubox/jshn.sh
./ipkg-install/usr/bin/jshn
./jshn.c
./CMakeFiles/jshn.dir
./CMakeFiles/jshn.dir/jshn.c.o

jshn.sh脚本,其实现是基于c语言jshn.c编译生成的命令行工具jshn,其基本思想是通过环境变量赋值最终组装成json串。

1.JSON的解析

如下是我要解析的数据

{
    "upload_speed": "30.77",
    "download_speed":       "87.21",
    "latency":      25,
    "code": 0
    "dev_info":{          
        "name":"test"
    }
}

下面是shell代码实现过程

#!/bin/sh

. /usr/share/libubox/jshn.sh

speedtest_result=$(/usr/bin/zspeedtest)
json_load "$speedtest_result"
json_get_var code code
if [ $code == 0 ]; then
    json_get_var upload_speed upload_speed
    uci set zqos.wan.upload_speed=${upload_speed}

    json_get_var download_speed download_speed
    uci set zqos.wan.download_speed=${download_speed}

    json_get_var latency latency
    uci set zqos.wan.latency=${latency}

    uci commit zqos
fi

#选择dev_info object
json_select dev-info
#读取dev_info.name
json_get_var name1 name
echo "name1 = $name1


2.JSON的组装

在发送ubus信息的时候一般都需要组装成json格式,字符串直接load成json:

#!/bin/sh

. /usr/share/libubox/jshn.sh

echo "power off"
json_init
json_load '{"msgType":"DEVICE_CONTROL","devId":"000d6f000b7a976b","prodTyp..."}'
ubus send iotcontrolreq "$(json_dump)"
sleep 2

response=`ubus listen /localhost/iot/status`
echo $response
SIGINT

echo "power on"
json_init
json_load '{"msgType":"DEVICE_CONTROL","devId":"000d6f000b7a976b","prodTyp..."}'
ubus send iotcontrolreq "$(json_dump)"
sleep 2
response=`ubus listen /localhost/iot/status`
echo $response
SIGINT


一个一个组装成json:

#!/bin/sh

. /usr/share/libubox/jshn.sh

json_init
json_add_string "upload_speed" "30.77"
json_add_string "download_speed" "87.21"
json_add_int "latency"  25
json_add_boolean "code" 0
echo "cur=$JSON_CUR"
json_add_object "dev_info" 
echo "cur=$JSON_CUR"
echo "cur=$JSON_CUR"
json_add_string "name" test
echo "cur=$JSON_CUR"
json_select ..
echo "cur=$JSON_CUR"
json_add_array  "array"
json_add_string "" "value1"
json_add_string "" "value2"
echo "cur=$JSON_CUR"
json_dump

结果

{
    "upload_speed": "30.77",
    "download_speed":       "87.21",
    "latency":      25,
    "code": 0
    "dev_info":{          
        "name":"test"
    },
	"array": ["value1", "value2"]
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值