DEV Community

karthik22061993
karthik22061993

Posted on

How to format the file containing json objects to json array

I am writing a javascript to format JSON objects to array of JSON objects.
My input is,
{
Name:"nom1",
Cities:['city1','city2']
}
{
Name:"nom2",
Cities:['city4','city5']
}

And I want the output as,

var data = [ { Name:"nom1", Cities:['city1','city2'] }, { Name:"nom2", Cities:['city3','city4'] } ]};

How to write a script to achieve this?

Top comments (1)

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)}]`)