How to Convert JavaScript JSON/Object to String

    Oct 15, 2020       by Pankaj Kumar

While working at server-side and creating REST API for different platforms like mobile, web etc. We use JSON format to send data from server to client. 

JSON is a common datatype to exchange the data from the client and server when we connect the two using REST Apis. While sending data from the client to a web server, the data must be a string.

 

JSON to String in JavaScript

JSON.stringify() is an inbuilt function in JavaScript which is used to convert JSON to Object. This method mainly converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

 

Example:

  let user = { name: "John", age: 27, address:"New Delhi, India" };
  let stringData = JSON.stringify(user)
  console.log(stringData);  //Output: {"name":"John","age":27,"address":"New Delhi, India"}

 

In the above example, We can see data in JSON format is converted to String format. 

Note: Any function inside the JSON/object is removed while using JSON.stringify().

 

Parsing JSON(Revert back String value to JSON)

JSON.parse() is an inbuilt javascript function which coverts String value to JSON/Object. It is used when stringify value is sent to server from client and needs to read the values to perform the further tasks.

let userString = '{"name":"John","age":27,"address":"New Delhi, India"}';
let jsonData = JSON.parse(userString);
console.log(jsonData); // Output: {name: "John", age: 27, address: "New Delhi, India"}

 

In the above example, We can see the Stringified value is reverted back to JSON. 

To get more depth knowledge, Click here

Thanks!


WHAT'S NEW

Find other similar Articles here: