How to convert JSON to JSON lines

2.4k views Asked by At

I am new to JavaScript. I am building an array of objects. I need to stringify it, get rid of the square brackets, and split each object on ',' and put on new line.

Need to go from:

[{"product_id":297316,"id":1,"rating":3},{"product_id":98133,"id":2,"rating":2}]

To this:

"{"product_id":297316,"id":1,"rating":3}",
"{"product_id":98133,"id":2,"rating":2}"
2

There are 2 answers

0
Ray Toal On BEST ANSWER

If by put on a new line you mean print, you can do:

for (let product of products) {
  console.log(JSON.stringify(product))
}

Or if you want to produce a newline-separated string you can do:

products.map(JSON.stringify).join('\n')
1
Chris Sum On

So.... I got that you need understand code lines for testing or what information comes from API or something like that.

Most of the time I use replace using regex in Sublime Text 3 in a fast way, like:

Example