Split JSON file into separate files

I have a large JSON file, which is an object of objects, which I would like to split into separate file names after the keys of the objects. Is it possible to achieve this using jq or any other off-the-shelf tools?

The original JSON is in the following format

{ "item1": {...}, "item2": {...}, ...}

Given this input, I would like to create the item1.json, item2.json files, etc.

+6
source share
2 answers

This should give you a start:

 for f in `cat input.json | jq -r 'keys[]'` ; do cat input.json | jq ".$f" > $f.json done 
+7
source

Here's a solution requiring only one jq call:

 jq -cr 'keys[] as $k | "\($k)\n\(.[$k])"' input.json | while read -r key ; do read -r item printf "%s\n" "$item" > "/tmp/$key.json" done 

It might be faster to execute jq command output on awk, for example:

 jq -cr 'keys[] as $k | "\($k)\t\(.[$k])"' input.json | awk -F\\t '{ print $2 > "/tmp/" $1 ".json" }' 

Of course, these approaches should be changed if key names contain characters that cannot be used in file names.

+2
source

Source: https://habr.com/ru/post/983043/


All Articles