Skip to content

Instantly share code, notes, and snippets.

@fprimex
Created April 5, 2020 14:18
Show Gist options
  • Save fprimex/e71526d6d1bbae814f263e3b8dc857c4 to your computer and use it in GitHub Desktop.
Save fprimex/e71526d6d1bbae814f263e3b8dc857c4 to your computer and use it in GitHub Desktop.
#!/bin/sh
makejs_arg () {
if [ "$1" = true ] || [ "$1" = false ] || [ "$1" = null ]; then
# TODO: ints/numbers
# non-quoted value
echo "$1"
else
# quoted value
#strip |tostring, wrap in quotes
echo "\"${1%|tostring}\""
fi
}
makejs () {
jqprog=""
while [ -n "$1" ]; do
if [ "$(echo "$1" | cut -c 2-)" = "[]" ]; then
# append to array
# key |= . + [value] |
jqprog="$(printf '%s\n%s |= . + [%s] |' "$jqprog" "$1" "$(makejs_arg $2)")"
shift
shift
else
#strip |tostring
#wrap in quotes
jqprog="$(printf '%s\n%s = %s |' "$jqprog" "$1" "$(makejs_arg $2)")"
shift
shift
fi
done
jqprog="$(printf '%s\ntostring' "$jqprog")"
echo "jq program is:"
echo "$jqprog"
echo
echo "Output is:"
echo
echo null | jq -r "$jqprog"
}
makejs .baz qux \
.foo[3] three \
.foo[2] null \
.one two \
.foo[] bar \
.foo2[0] f2
$ ./genjs.sh
jq program is:
.baz = "qux" |
.foo[3] = "three" |
.foo[2] = null |
.one = "two" |
.foo[] = "bar" |
.foo2[0] = "f2" |
tostring
Output is:
{"baz":"qux","foo":["bar","bar","bar","bar"],"one":"two","foo2":["f2"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment