X-Git-Url: http://git.plutz.net/?a=blobdiff_plain;f=json.sh;h=12afdc4d676b94b705b0c165fee2512c80891cb9;hb=6c558265e3db741077c1356d46fe6e7e904dc814;hp=ba1539adf7fb47b87013f7f0869e9aeee7fc2cac;hpb=e1c0b4bed53401e2dfb5bfd3c561587db7e0e212;p=cgilite diff --git a/json.sh b/json.sh index ba1539a..12afdc4 100755 --- a/json.sh +++ b/json.sh @@ -95,7 +95,7 @@ json_number() { } json_array() { - local struct="$(DB2 new)" value json_document="$json_document" + local struct="$(DB2 "" new)" value json_document="$json_document" json_space case $json_document in @@ -141,7 +141,7 @@ json_array() { } json_object() { - local struct="$(DB2 new)" key value json_document="$json_document" + local struct="$(DB2 "" new)" key value json_document="$json_document" json_space case $json_document in @@ -300,3 +300,61 @@ json_get() { json_get "$json" "$jpath" return $? } + +json_dump_string() { + local in="$1" out='' + while [ "$in" ]; do case $in in + \\*) out="${out}\\\\"; in="${in#\\}" ;; + "$BR"*) out="${out}\\n"; in="${in#${BR}}" ;; + "$CR"*) out="${out}\\r"; in="${in#${CR}}" ;; + " "*) out="${out}\\t"; in="${in# }" ;; + \"*) out="${out}\\\""; in="${in#\"}" ;; + *) out="${out}${in%%[\\${CR}${BR} \"]*}"; in="${in#"${in%%[\\${BR}${CR} \"]*}"}" ;; + esac; done + printf '"%s"' "${out}" +} + +json_dump_array() { + local json="$1" value out='' + + for value in $(DB2 "$json" iterate @); do + out="${out},$(json_dump "$(UNSTRING "$value")")" + done + printf '[%s]' "${out#,}" +} + +json_dump_object() { + local json="$1" key value out='' + + while read -r key value; do + out="${out},$(json_dump_string "$(UNSTRING "$key")"):$(json_dump "$(UNSTRING "$value")")" + done <<-EOF + ${json} + EOF + printf '{%s}' "${out#,}" +} + +json_dump() { + local json="$1" + + case $json in + str:*) + json_dump_string "${json#str:}" + ;; + arr:*) + json_dump_array "${json#arr:}" + ;; + obj:*) + json_dump_object "${json#obj:}" + ;; + num:*) + printf "${json#num:}" + ;; + true|false|null) + printf %s\\n "$json" + ;; + *) + json_dump_string "${json}" + ;; + esac +}