Last active
November 28, 2020 11:32
-
-
Save peet86/0cd7e06e863c4a3f37f70fb2d5a15f4b to your computer and use it in GitHub Desktop.
Split JSON array to files, use attribute as filename
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
#!/bin/bash | |
# Split JSON array to files, use json attribute as filename | |
# | |
# input.json: | |
# [ | |
# {"id":"1", "name":"first"}, | |
# {"id":"1", "name":"second"}, | |
# ... | |
# ] | |
# | |
# ./split.sh /path/to/input.json name | |
# | |
# Output: | |
# | |
# first.json // {"id":"1", "name":"first"} | |
# second.json // {"id":"2", "name":"second"} | |
# ... | |
input="$1" | |
name="$2" | |
dir=$(dirname "$input") | |
echo $output | |
jq -cr 'keys[] as $k | "\($k)\n\(.[$k])"' "$input" | while read -r key; do | |
filename=$(jq --raw-output ".[$key].$name" $input) | |
read -r item | |
printf '%s\n' "$item" > "$dir/$filename.json" | |
echo "$filename.json" | |
done | |
echo "> done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment