Using .id
as part of a filename is fraught with risk.
First, there is the potential problem of embedded newline characters.
Second, there is the problem of "reserved" characters, notably "/".
Third, Windows has numerous restrictions on file names -- see e.g. https://gist.github.com/doctaphred/d01d05291546186941e1b7ddc02034d3).
Also, if jq's -r option is used, as suggested in another posting on this page, then .id values of "1"
and 1
will both be mapped to 1
, which will result in loss of data if ">" is used in awk.
So here is a solution that illustrates how safety can be achieved in an OS X or *ix environment and that goes a long way towards a safe solution for Windows:
jq -c '.[]
| (.id | if type == "number" then .
else tostring | gsub("[^A-Za-z0-9-_]";"+") end), .' |
awk '
function fn(s) { sub(/^\"/,"",s); sub(/\"$/,"",s); return s ".json"; }
NR%2{f=fn($0); next}
{print >> f; close(f);}
'
Notice especially the use of ">>" to avoid losing data in the case of file name collisions.