Created
June 25, 2019 19:18
-
-
Save paulstuart/6dfddc5143d1227e1874c7dc561361ef to your computer and use it in GitHub Desktop.
A script to "flatten" and "unflatten" JSON structures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks for sharing!