jsonjsonlines

How to convert JSON to JSON lines


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}"

Solution

  • 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')