DEV Community

Discussion on: How to format the file containing json objects to json array

Collapse
 
savagepixie profile image
SavagePixie • Edited

Assuming that your file is actual json and that's the input of the function (i.e., you're not parsing it before) and that json objects will always be separated by a new line, something like this should do the trick:

const addCommas = jsonStr => jsonStr.replace('}\n{', '},{')
const jsonArray = jsonStr => `[${addCommas(jsonStr)}]`

If you want it to return an actual array, rather than a json array, you can simply do:

const addCommas = jsonStr => jsonStr.replace('}\n{', '},{')
const jsonArray = jsonStr => JSON.parse(`[${addCommas(jsonStr)}]`)