How To Convert An Object To JSON String Using JavaScript

Convert an Object to JSON String using JavaScript

JSON is a standard data format, we use it to exchange data on the web. If you want to convert an Object to JSON string using JavaScript, read the whole article.

To Convert An Object To JSON String Using JavaScript?

To convert a JavaScript object into a JSON string, JavaScript provides you with a method called JSON.stringify().

Syntax:

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

Let’s go through all the use cases of this statement.

Example using the first syntax:

const myObj = {
	name: "Hoan",
	academic: "HUST",
	major: "IT",
}

console.log(myObj)
console.log(typeof myObj)

const myNewObj = JSON.stringify(myObj)

console.log(myNewObj)
console.log(typeof myNewObj)

Output:

{ name: 'Hoan', academic: 'HUST' major: 'IT' }
object
{"name":"Hoan","academic":"HUST","major":"IT"}
string

As you can see, the JSON.stringify() method helped us to convert an object to a JSON string. The data type of myObj changed from object to string, and the data is stored in JSON format.

Example using the second syntax:

The second parameter is a replacer function, which takes a key/value pair that can be used to change the final output.

const myObj = {
	name: "Hoan",
	academic: "HUST",
	major: "IT",
}

const myNewObj = JSON.stringify(myObj,
	function replacer(key, value) {
		if (key == 'name') {
			return 'Mr.' + value
		}

		return value
	})

console.log(myNewObj)

Output:

{"name":"Mr.Hoan","academic":"HUST","major":"IT"}

Example for the last syntax:

The third parameter is spaces, which allows formatting the code printed to the console – a better way to visualize the output.

const myObj = {
  	name: "Hoan",
	academic: "HUST",
	major: "IT",
}

const myNewObj = JSON.stringify(myObj,
	function replacer(key, value) {
		if (key == 'name') {
			return 'Mr.' + value
		}

		return value
	}, 2)

console.log(myNewObj)

Output:

{
   "name": "Mr.Hoan", 
   "academic": "HUST",
   "major": "IT"      
}

For more information, in case you want to do opposite work, check out this method: JSON.parse().

Summary

Finally, I introduce an effortless method that helps you to convert an object to JSON string using JavaScript. Thanks for your interest!

Maybe you are interested:

Leave a Reply

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