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

139
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
get_co
;;
"}")
imoo=0
get_lo
;;
"\"")
if [ $imosv -eq 1 ]
then then
imosv=0 addword $char
echo "$cv: $csv"
elif [ $imoas -eq 1 ]
then
imoas=0
imosv=1
cv="$cas"
else
imoas=1
fi fi
;; ;;
":") # Works in bash, not in sh.
echo "Ignore" > /dev/null # [[:alpha:]])
[ABCDEFGHIJKLMNOPQRSTUVWXYZ])
addword $char
;; ;;
",") [abcdefghijklmnopqrstuvwxyz])
echo "Ignore" > /dev/null addword $char
;; ;;
*) # [[:digit:]])
if [ $imoas -eq 1 ] [0123456789])
if [ $NEWWORD -eq 1 ]
then then
cas="${cas}${char}" addword $char
elif [ $imosv -eq 1 ]
then
csv="${csv}${char}"
else else
echo "Ignored: $char" TYPE="number"
startword
addword $char
fi fi
;; ;;
[,])
if [ $NEWWORD -eq 1 ] && [ $TYPE == "string" ]
then
addword $char
elif [ $NEWWORD -eq 1 ] && [ $TYPE == "number" ]
then
endword
fi
;;
\")
if [ $NEWWORD -eq 1 ]
then
endword
else
TYPE="string"
startword
fi
;;
':')
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 esac
echo "$char | $imov $imosv $imoo $imoas" done < "$1"
done }
json $1