Skip to content

Instantly share code, notes, and snippets.

@emanuele6
Last active June 21, 2024 05:45
Show Gist options
  • Save emanuele6/328119cf459a68c80d34818881b3fdff to your computer and use it in GitHub Desktop.
Save emanuele6/328119cf459a68c80d34818881b3fdff to your computer and use it in GitHub Desktop.
gron in jq
#!/bin/sh --
# \
exec jq -nsRrf "$0" --args -- "$@"
def path2gronpath:
reduce .[] as $k ("json"; . + ($k |
if type == "number" or . == "" or test("^[0-9]|[^0-9a-zA-Z_]")
then @json "[\(.)]"
else ".\(.)"
end));
def togron:
path(..) as $p | "\($p | path2gronpath) = \(
getpath($p) | if type == "array"
then "[]"
elif type == "object"
then "{}"
else tojson
end);";
def fromgron(gron):
def _fromgron:
if startswith("json") then
[ .[4:] | _fromgron ]
elif startswith(".") then
scan("^\\.([a-zA-Z_][0-9a-zA-Z_]*)(.*)") |
.[0], (.[1] | select(. != "") | _fromgron)
elif startswith("[") then
. as $dot |
first(indices("]")[] as $i |
.[:$i + 1] | fromjson? |
. + [ $dot[$i + 1:] ]) |
.[0], (.[1] | _fromgron)
else
ltrimstr(" = ") | rtrimstr(";") | fromjson
end;
reduce gron as $g (null;
($g | _fromgron) as $pg |
setpath($pg[:-1]; $pg[-1]));
if $ARGS.positional == [] then
try
(input | fromjson | togron)
catch
(@json "Invalid input: \(.).\n" | halt_error)
elif $ARGS.positional == [ "-u" ] then
fromgron((input / "\n")[] | select(. != "")) | tojson
else
@json "Invalid arguments: \($ARGS.positional)\n" | halt_error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment