很多情况下我们需要在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


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


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


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"]
}