Convert JavaScript Object to JSON String

by Vincy. Last modified on October 26th, 2022.

JSON string conversion on the client and server side is an important requirement in data handling. Most programming languages contain native functions for handling JSON objects and string data.

The JSON format is a convenient way of structuring, transmitting, or logging hierarchical data. The JSON string is a bundled unit to transmit object properties over the API terminals.

In this tutorial, we will see how to convert a JavaScript object to a JSON string. The JSON.stringify() of the JS script is used to do this. This is a quick solution for converting the given JS object to a JSON.

Quick example

var jsObject = {
	"name": "Lion",
	"type": "wild"
};
var jsonString = JSON.stringify(jsObject)
console.log(jsonString);

Output

{"name":"Lion","type":"wild"}

javascript object to string

About JavaScript JSON.stringify()

The JSON.stringify() method accepts 3 parameters to convert JavaScript objects into JSON string. See the syntax and the possible parameters of this JavaScript method.

Syntax

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)

The replacer and space parameters are optional.

  • value – The JS object to be converted to a JSON string.
  • replacer – a  function or an array of specifications to convert JavaScript objects.
  • space – It is a specification used to format or prettify the output JSON.

The JSON.stringify() method can also accept JavaScript arrays to convert into JSON strings.

How to get a formatted JSON string from a JavaScript object

This example supplies the “space” parameter to the JSON.stringify method. This parameter helped to format the JSON string as shown in the output below the program.

When we see the PHP array to JSON conversion example, it used the PHP bitmask parameter to achieve prettyprinting of JSON output.

var jsObject = {
	"name": "Lion",
	"type": "wild"
};

// this is to convert a JS object to a formatted JSON string
var formattedJSON = JSON.stringify(jsObject, null, 2);
console.log(formattedJSON);

Output

{
  "name": "Lion",
  "type": "wild"
}

How to store JSON string to a JavaScript localStorage

The localStorage is a mechanism to have persistent data or state on the client side. It accepts string data to be stored with a reference of a user-defined key.

In this example, we used this storage tool to keep the JSON string of cart session data.

This code pushes two records to the cart array. Then, it converts the array into the JSON string to put it into the localStorage.

Note: JSON.stringify() can also accepts array to convert into a JSON string.

We have already used this storage mechanism to create a JavaScript persistent shopping cart.

const cart = {
	cartItem: []
};
cart.cartItem.push({ product: "Watch", quantity: 3, unitPrice: 100 });
cart.cartItem.push({ product: "Smart Phone", quantity: 5, unitPrice: 600 });

// use case for converting JS object to a JSON string
// convert object to JSON string before storing in local storage
const cartJSONString = JSON.stringify(cart);

localStorage.setItem("cartSession", JSON.stringify(cartJSONString));

// retrieving from local storage
let cartFromStorage = localStorage.getItem("cartSession");
const getCartItemFromSession = JSON.parse(cartFromStorage);

console.log(getCartItemFromSession);

Output

{
   "cartItem":
   [
      {"product":"Watch","quantity":3,"unitPrice":100},
      {"product":"Smart Phone","quantity":5,"unitPrice":600}
   ]
}

How dates in the JavaScript object behave during JSON stringify

The JSON.stringify() function converts the JavaScript Date object into an equivalent date string as shown in the output.

The code instantiates the JavaScript Date() class to set the current date to a JS object property.

// when you convert a JS object to JSON string, date gets automatically converted
// to equivalent string form
var jsObject = {
	"name": "Lion",
	"type": "wild",
	today: new Date()
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);

Output

{"name":"Lion","type":"wild","today":"2022-10-23T10:58:55.791Z"}

How JSON stringify converts the JavaScript objects with functions

If the JS object contains functions as a value of a property, the JSON.stringify will omit the function. Then, it will return nothing for that particular property.

The resultant JSON string will have the rest of the properties that have valid mapping.

// when you convert a JS object to JSON string, 
// functions in JS object is removed by JSON.stringify 
var jsObject = {
	"name": "Lion",
	"type": "wild",
	age: function() {
		return 10;
	}
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);

Output

{"name":"Lion","type":"wild"}

JavaScript toString() limitations over JSON.stringify: 

If the input JavaScript object contains a single or with a predictable structure, toString() can achieve this conversion.

It is done by iterating the JS object array and applying stringification on each iteration. Example,

let jsonString = {
  'name': 'Lion',
  type: 'wild',

  toString() {
    return '{name: "${this.name}", age: ${this.type}}';
  }
};
console.log(jsonString);

But, it is not an efficient way that has the probability of missing some properties during the iteration.

Why and how to convert the JSON string into a JSON object

The JSON string is a comfortable format during data transmission and data logging. Other than that it must be in a format of an object tree to parse, read from, and write to the JSON.

The JSON.parse() method is used to convert JSON String to a JSON Object. A JSON object will look like a JS object only. See the following comparison between a JS object and a JSON object.

//JavaScript object
const jsObject = {
  'animal-name': 'Lion',
  animalType: 'wild',
  endangered: false
}

//JSON object
{
  "animal-name": "Lion",
  "animalType": "wild",
  "endangered": false
}

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page