Skip to content

Instantly share code, notes, and snippets.

@peet86
Last active November 28, 2020 11:32
Show Gist options
  • Save peet86/0cd7e06e863c4a3f37f70fb2d5a15f4b to your computer and use it in GitHub Desktop.
Save peet86/0cd7e06e863c4a3f37f70fb2d5a15f4b to your computer and use it in GitHub Desktop.
Split JSON array to files, use attribute as filename
#!/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