Split a JSON file into separate files

前端 未结 3 1906
野性不改
野性不改 2020-12-03 17:52

I have a large JSON file that is an object of objects, which I would like to split into separate files name after object keys. Is it possible to achieve this using jq or any

3条回答
  •  春和景丽
    2020-12-03 18:33

    Here's a solution that requires only one call to jq:

    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 pipe the output of the jq command to awk, e.g.:

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

    Of course, these approaches will need to be modified if the key names contain characters that cannot be used in filenames.

提交回复
热议问题