Skip to content

Instantly share code, notes, and snippets.

@definiteIymaybe
Created November 16, 2023 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save definiteIymaybe/df38669d2521a19f94fc3ece50c9ee5e to your computer and use it in GitHub Desktop.
Save definiteIymaybe/df38669d2521a19f94fc3ece50c9ee5e to your computer and use it in GitHub Desktop.
jq flatten json recursively
# concise version:
# 'map(def flatten($prefix): . as $in | reduce keys[] as $key ({}; . + (if ($in[$key] | type) == "object" then $in[$key] | flatten(($prefix + $key + ".")) else {($prefix + $key): $in[$key]} end));flatten(""))'
# unwrapped for readabiliy:
map(
# Recursive function to flatten an object
def flatten($prefix):
. as $in
| reduce keys[] as $key (
{}; . + (
# Check if the value is an object and needs further flattening
if ($in[$key] | type) == "object" then
$in[$key] | flatten(($prefix + $key + "."))
# If it's not an object, add it to the output
else
{($prefix + $key): $in[$key]}
end
)
);
# Apply the function to each item in the array
flatten("")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment