Archived
1
0
Disbranĉigi 0

Full read support of JSON files

This commit is contained in:
Jaidyn Ann 2017-03-25 13:58:46 -05:00
parent 23611b0029
commit c347eb502b
2 changed files with 105 additions and 66 deletions

12
example.json Normal file
View File

@ -0,0 +1,12 @@
{
"animals": {
"pig": {
"tail": "curly",
"nose": "adorable"
},
"sheep": {
"tail": "short",
"nose": "ugly"
}
}
}

159
json.sh
View File

@ -1,74 +1,101 @@
#!/bin/sh #!/bin/sh -ex
# WIP JSON parser
# OK, this is going to be a convoluted state machine based on the following states: JGROUPS=''
imov=0 # in middle of variable [ "variable" = "..." ] GROUPORVAR=0
imosv=0 # in middle of string value [ "..." = "value" ] NEWWORD=0
imoo=0 # in middle of object [ "object" {...} ]
imoas=0 # in middle of ambiguous string
# And using the following vars:
cv='' # current variable
lv='' # last variable
csv='' # current string value
lsv='' # last string value
co='' # current object
lo='' # last object
aco='' # all current objects
cas='' # current abiguous string
endword() {
get_co() { NEWWORD=0
aco="$aco/$cas" if [ $GROUPORVAR -eq 1 ]
co=$(echo "$aco" | sed 's^.*/^^') then
echo "${JGROUPS}/$LASTWORD = $CURWORD"
GROUPORVAR=0
else
echo "${JGROUPS}/$CURWORD"
fi
LASTWORD=$CURWORD
CURWORD=''
TYPE=''
} }
get_lo() { startword() {
lo=$co NEWWORD=1
aco=$(echo "$aco" | sed 's^/'"$lo"'^^')
} }
addword() {
CURWORD="${CURWORD}${1}"
}
json() {
for char in $(cat $1 | sed 's/\(.\)/\1 /g') for char in $(cat $1 | sed 's/\(.\)/\1 /g')
do do
case $char in case "$char" in
"{") ' ')
imoas=0 if [ $NEWWORD -eq 1 ] && [ $TYPE == "string" ]
imoo=1 then
get_co addword $char
;; fi
"}") ;;
imoo=0 # Works in bash, not in sh.
get_lo # [[:alpha:]])
;; [ABCDEFGHIJKLMNOPQRSTUVWXYZ])
"\"") addword $char
if [ $imosv -eq 1 ] ;;
then [abcdefghijklmnopqrstuvwxyz])
imosv=0 addword $char
echo "$cv: $csv" ;;
elif [ $imoas -eq 1 ] # [[:digit:]])
then [0123456789])
imoas=0 if [ $NEWWORD -eq 1 ]
imosv=1 then
cv="$cas" addword $char
else else
imoas=1 TYPE="number"
fi startword
;; addword $char
":") fi
echo "Ignore" > /dev/null ;;
;; [,])
",") if [ $NEWWORD -eq 1 ] && [ $TYPE == "string" ]
echo "Ignore" > /dev/null then
;; addword $char
*) elif [ $NEWWORD -eq 1 ] && [ $TYPE == "number" ]
if [ $imoas -eq 1 ] then
then endword
cas="${cas}${char}" fi
elif [ $imosv -eq 1 ] ;;
then \")
csv="${csv}${char}" if [ $NEWWORD -eq 1 ]
else then
echo "Ignored: $char" endword
fi else
;; TYPE="string"
esac startword
echo "$char | $imov $imosv $imoo $imoas" fi
done ;;
':')
GROUPORVAR=1
;;
'{')
if [ $GROUPORVAR -eq 1 ]
then
CURGROUP="${LASTWORD}"
JGROUPS="${JGROUPS}/${CURGROUP}"
GROUPORVAR=0
fi
;;
'}')
if [ $NEWWORD -eq 1 ] && [ $TYPE == "number" ]
then
endword
fi
JGROUPS=$(echo $JGROUPS | sed 's@/'$CURGROUP'$@@')
CURGROUP=$(echo $JGROUPS | grep -oE '[^/]+$')
;;
esac
done < "$1"
}
json $1