OpenWrt開發教程(五)shell命令操作json api詳解(jshn.sh)


摘自:https://blog.csdn.net/dxt1107/article/details/86587541

json已經成為了通用的接口格式,各個語言中都有好用的json庫,相信大家也都用得比較熟練。
但在某些情況下我們需要在shell下操作json,如OpenWrt系統中在shell中封裝ubus消息。
OpenWrt shell操作json腳本在/usr/share/libubox/jshn.sh文件中,其實現是基於c語言的命令行工具。
其基本思想是通過環境變量賦值最終組裝成json串。
下面介紹jshn.sh api接口的使用方法,並給出幾個實例

支持的數據類型

  1. string
  2. int
  3. boolean
  4. double

api接口說明

接口 說明 例子
json_add_object 添加一個對象 json_add_object obj1
json_add_string 添加string變量 json_add_string “name” “derry”
json_add_int 添加一個對象 json_add_int “id” 111
json_add_boolean 添加布爾變量 json_add_int “enable” 1
json_add_array 添加數組 json_add_array “array”
json_dump 顯示當前的json串  
json_select 切換到某個對象,有時候需要返回到上級對象操作 json_select dev-info
json_get_var 獲取某個變量值  
json_init 初始化環境變量  

讀取json文件實例

下面的例子用於讀取一個json變量,並有json_select的使用方法

json配置文件

{
        "name":"Derry",
        "dev_info":{          
                "name":"OpenWrt"
        }
}

 

讀取以上配置文件shell腳本

. /usr/share/libubox/jshn.sh
json_load "$(cat /etc/derry/test.json)"
#讀取第一層的name, name=Derry
json_get_var name1 name
echo "name1 = $name1"
#選擇dev_info object
json_select dev-info
#讀取dev_info.name
json_get_var name2 name
echo "name2 = $name2"

 

運行結果如下:

name1 = Derry
name2 = OpenWrt

 

封裝json

例子程序

. /usr/share/libubox/jshn.sh
json_init
json_add_string "name" "Derry"
json_add_int "id"  10
json_add_boolean "enable" 1
json_add_double "money" 10000000.08
echo "cur=$JSON_CUR"
json_add_object "class" 
echo "cur=$JSON_CUR"
echo "cur=$JSON_CUR"
json_add_int "cls_id" 1001
json_add_int "cls_name"  "class 1"
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

 

運行結果(可以根據結果找到以上對應代碼照寫即可)

{
	"name": "Derry",
	"id": 10,
	"enable": true,
	"money": 10000000.080000,
	"class": {
		"cls_id": 1001,
		"cls_name": 0
	},
	"array": ["value1", "value2"]
}

 

OpenWrt下讀取uci文件並封裝成json格式串

uci配置文件:

config appfilter appfilter
	option enable 1
	option appid_list "11 22 33 44 55 66"

 

腳本文件:

. /usr/share/libubox/jshn.sh
. /lib/functions.sh
json_init

config_load appfilter
config_get enable  "appfilter" enable
config_get appid_list "appfilter" appid_list

json_add_int "enable" $enable
json_add_array "appid"
for appid in $appid_list:
do
	echo "appid = $appid"
	json_add_int "" $appid
done

json_str=`json_dump`
echo "json=$json_str"

 

運行結果

appid = 11
appid = 22
appid = 33
appid = 44
appid = 55
appid = 66:
json={ "enable": 1, "appid": [ 11, 22, 33, 44, 55, 66 ] }

 

以上為個人總結的OpenWrt shell json庫使用方法,都是經過實測,如果對你有用,可以關注微信公眾號 OpenWrt 獲取更多OpenWrt開發技術文章,定期會發布OpenWrt相關干貨


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM