参考: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