JSON to String JavaScript

Last Updated On Sunday 17th Oct 2021

JS JSON to String

  • Morever all thecurrent browsers have native JSON support built in.
  • You can use JSON.stringify() method to convert JSON object to String.

The JSON.stringify() method converts a JavaScript object or value to a JSON string.

Syntax

	JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
	
  • value – The value to convert to a JSON string.
  • replacer – Selecting/Filtering the properties of the value object.
  • space – Used to insert white space into the output JSON string for readability purposes.

Object to JSON JavaScript

	JSON.stringify({"key":"value"});
	
	let me = {
  "name": "CJ"
};
console.log(JSON.stringify(me));
	
  • If You need more readable json string You can use space parameter like below
	let me = {
  "name": "CJ"
};
console.log(JSON.stringify(me, null, 2 ));
	

json to string javascript

  • The Above Code would give you beautified JSON.
  • As i Said above The second parameter is replacer. used as Filter where you can filter out certain key values when stringifying.
  • If set to null it will return all key value pairs

References