Created
November 16, 2023 11:59
-
-
Save definiteIymaybe/df38669d2521a19f94fc3ece50c9ee5e to your computer and use it in GitHub Desktop.
jq flatten json recursively
This file contains 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
# 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