一. 前言
jshn是一个小工具,用于解析或生成JSON格式的数据的,它的源代码位于libubox的jshn.c。jshn.sh是jshn的一个封装的脚本,位于openwrt系统的/usr/share/libubox/下。jshn.sh脚本主要让openwrt的脚本调用的来生成和解析json的,下面介绍shn工具和jshn.sh脚本的接口。
二. jshn.sh脚本分析
接下来以一个脚本讲解jshn.sh脚本的一些函数的用法。脚本首先构建一个内容为"{ "msg": "Hello, world!", "test": { "testdata": 1 }, "lan": [ "192.168.1.1", "192.168.10.1", "192.168.100.1" ] }"的json字符串,然后再解析其中的每个成员。
案例:
#!/bin/sh
# source jshn shell library
. /usr/share/libubox/jshn.sh
# generating json data
json_init
json_add_string "msg" "Hello, world!"
json_add_object "test"
json_add_int "testdata" "1"
json_close_object
json_add_array lan
json_add_string 1 "192.168.1.1"
json_add_string 2 "192.168.10.1"
json_add_string 3 "192.168.100.1"
json_close_array
MSG=`json_dump`
# MSG now contains: { "msg": "Hello, world!", "test": { "testdata": 1 }, "lan": [ "192.168.1.1", "192.168.10.1", "192.168.100.1" ] }
# parsing json data
json_load "$MSG"
json_select test
json_get_var var1 testdata
json_select ..
json_get_var var2 msg
echo "msg: $var2 - testdata: $var1"
json_select lan
idx=1
while json_is_a $idx string
do
json_get_var item $idx
echo $item
idx=$((idx+1))
done
. /usr/share/libubox/jshn.sh
引用jshn.sh脚本的接口,jshn.sh在此处展开。
json_init
初始化一个json实例。
json_add_string "msg" "Hello, world!"
添加一个字符串json对象,“msg”:"Hello,world"。
json_add_object "test"
添加一个test的json对象。
json_add_int "testdata" "1"
往test json对象里面添加整数形对象,"testdata":1。
json_close_object
关闭test对象。json_add_object添加对象后,后面必须调用json_close_object关闭对象。
json_add_array lan
添加一个数组json对象,命名为lan。
json_add_string 1 "192.168.1.1"
json_add_string 2 "192.168.10.1"
json_add_string 3 "192.168.100.1"
添加数组的第1,2,3项分别为"192.168.1.1","192.168.10.1"和"192.168.100.1"。
MSG=`json_dump`
json_dump会以字符串打印上面添加的json数据,此处表示打印的内容赋值给MSG变量。内容为{ "msg": "Hello, world!", "test": { "testdata": 1 }, "lan": [ "192.168.1.1", "192.168.10.1", "192.168.100.1" ] }。
json_load "$MSG"
json_load用于解析json字符串为json对象。
json_select test
选择test json对象。注意:如果json对象是多层嵌套的,json_select每次只能选择一层,如果要获取最里面一层,json_select必须操作多次。
json_get_var var1 testdata
json_get_var用于获取testdata的值保存在var1中。
json_select ..
json_select选择上一层对象。
json_get_var var2 msg
json_get_var用于获取msg的值保存在var2中。
json_select lan
选择lan数组json对象。
idx=1
初始化索引号为1,idx表示数组的下标。
while json_is_a $idx string
json_is_a用于判断某个json变量的类型,此处用于判断lan数组json对象的第idx项是不是数组类型。
json_get_var item $idx
echo $item
获取数组json对象第idx项的值,并赋值到item变量,并输出。
idx=$((idx+1))
idx的值自加1。
三. 总结
本文以一个脚本案例讲解jshn.sh的一些函数的用法,先通过添加函数构建一个json对象,然后通过解析函数获取各个json对象的值,加深对jshn.sh函数的熟悉。