Converting JavaScript Objects to JSON

Node allows you to convert a JavaScript object into a properly formatted JSON string. Thus you can store the string form in a file or database, send it across an HTTP connection, or write it to a stream or buffer. You use the JSON.stringify(object) method to parse a JavaScript object and generate a JSON string. For example, the following code defines a JavaScript object that includes string, numeric, and array properties. JSON.stringify() converts it to a JSON string:

var accountObj = {  name: "Baggins",  number: 10645,  members: ["Frodo, Bilbo"],  location: "Shire"};var accountStr = JSON.stringify(accountObj);console.log(accountStr);

The above snippet outputs the following: ...

Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.