Is it possible to achieve this using jq or any other off-the-shelf tools?
It is. The command-line JSON-parser xidel can help out.
Let's assume 'input.json':
{
"item1": {
"a": 1
},
"item2": {
"b": 2
},
"item3": {
"c": 3
}
}
You could use Bash, as the other answers lay out...
$ for f in $(xidel -s "input.json" -e '$json()'); do
xidel -s "input.json" --variable f="$f" -e '$json($f)' > "$f.json"
done
$ xidel -s "input.json" -e '$json() ! (.,serialize($json(.),{"method":"json"}))' |
while read -r key ; do read -r item; printf "%s\n" "$item" > "$key.json"; done
...but with the integrated EXPath File Module Xidel can also do this very efficiently:
$ xidel -s "input.json" -e '
$json() ! file:write(`{.}.json`,$json(.),{"method":"json"})
'
$ xidel -s item[123].json -e '$raw'
{"a":1}
{"b":2}
{"c":3}
$ xidel -s "input.json" -e '
$json() ! file:write(`{.}.json`,$json(.),{"method":"json","indent":true()})
'
$ xidel -s item[123].json -e '$raw'
{
"a": 1
}
{
"b": 2
}
{
"c": 3
}