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:
imov=0 # in middle of variable [ "variable" = "..." ]
imosv=0 # in middle of string value [ "..." = "value" ]
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
JGROUPS=''
GROUPORVAR=0
NEWWORD=0
get_co() {
aco="$aco/$cas"
co=$(echo "$aco" | sed 's^.*/^^')
endword() {
NEWWORD=0
if [ $GROUPORVAR -eq 1 ]
then
echo "${JGROUPS}/$LASTWORD = $CURWORD"
GROUPORVAR=0
else
echo "${JGROUPS}/$CURWORD"
fi
LASTWORD=$CURWORD
CURWORD=''
TYPE=''
}
get_lo() {
lo=$co
aco=$(echo "$aco" | sed 's^/'"$lo"'^^')
startword() {
NEWWORD=1
}
addword() {
CURWORD="${CURWORD}${1}"
}
json() {
for char in $(cat $1 | sed 's/\(.\)/\1 /g')
do
case $char in
"{")
imoas=0
imoo=1
get_co
;;
"}")
imoo=0
get_lo
;;
"\"")
if [ $imosv -eq 1 ]
case "$char" in
' ')
if [ $NEWWORD -eq 1 ] && [ $TYPE == "string" ]
then
imosv=0
echo "$cv: $csv"
elif [ $imoas -eq 1 ]
then
imoas=0
imosv=1
cv="$cas"
else
imoas=1
addword $char
fi
;;
":")
echo "Ignore" > /dev/null
# Works in bash, not in sh.
# [[:alpha:]])
[ABCDEFGHIJKLMNOPQRSTUVWXYZ])
addword $char
;;
",")
echo "Ignore" > /dev/null
[abcdefghijklmnopqrstuvwxyz])
addword $char
;;
*)
if [ $imoas -eq 1 ]
# [[:digit:]])
[0123456789])
if [ $NEWWORD -eq 1 ]
then
cas="${cas}${char}"
elif [ $imosv -eq 1 ]
then
csv="${csv}${char}"
addword $char
else
echo "Ignored: $char"
TYPE="number"
startword
addword $char
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
echo "$char | $imov $imosv $imoo $imoas"
done
done < "$1"
}
json $1