Convert JavaScript Objects to JSON

The advantage of converting a JavaScript object into a properly formatted JSON string is that it makes it simple to store the string form in a file or database, send it across an HTTP connection, or write it to a stream or buffer.

The JSON.stringify(object) method can be used to parse a JavaScript object and generate a JSON string.

var accountObj = {
  name: "Randy",
  number: 111,
  members: ["Bill, Smith"],
  location: "London"
var accountStr = JSON.stringify(accountObj);

The output:

{"name":"Randy","number":111,"members":["Bill, Smith"],"location":"London"}

Enjoyed this post? Share it!