Skip to content

Instantly share code, notes, and snippets.

@paulstuart
Created June 25, 2019 19:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulstuart/6dfddc5143d1227e1874c7dc561361ef to your computer and use it in GitHub Desktop.
Save paulstuart/6dfddc5143d1227e1874c7dc561361ef to your computer and use it in GitHub Desktop.
A script to "flatten" and "unflatten" JSON structures
#!/bin/bash
# Convert json data to a dotted notation for line-based manipulation and visualization
#
# Adapted from dialog here: https://news.ycombinator.com/item?id=20245913
# jq code by @jolmg
#
flat() {
jq -r '
tostream
| select(length > 1)
| (
.[0] | map(
if type == "number"
then "[" + tostring + "]"
else "." + .
end
) | join("")
) + " = " + (.[1] | @json)
' $@
}
fat() {
# bsd sed chokes on our the append '$a.', so we have a kludge for it
# gsed is gnu-sed, and we're not guaranteed to have it.
# keeping it here and commented out as a reminder to remedy someday
#jq "$(gsed 's/$/ |/; $a.')" <<< '{}'
jq "$(sed -e 's/$/ |/' ; echo "." )" <<< '{}'
}
if [[ $1 == "-u" ]]; then
shift
fat $@
exit
fi
flat $@
@nnsense
Copy link

nnsense commented Mar 25, 2023

Nice, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment