AppDividend
Latest Code Tutorials

How to Convert Javascript JSON to String

0

JSON is a common datatype to exchange the data from the client and server. When we want to send data from the client to a web server, the data must be a string.

Javascript JSON to String

To convert a JavaScript object to string, use the JSON.stringify() function. The JSON.stringify() method converts JavaScript object into string.

Let’s stringify the Javascript Object.

// app.js

let obj = { name: "Krunal", age: 27, city: "Rajkot" };
let myJSON = JSON.stringify(obj)
console.log(myJSON)

Output

{"name":"Krunal","age":27,"city":"Rajkot"}

You can see that myJSON will be a string following the JSON notation.

In JSON, functions are not allowed as object values. The JSON.stringify() function removes any functions from a JavaScript object, both the key and the value.

// app.js

let obj = { name: "Krunal", age: function () { return 30; }, city: "Rajkot" };
let myJSON = JSON.stringify(obj);
console.log(myJSON)

Output

{"name":"Krunal","city":"Rajkot"}

You can see that the function is removed from the myJSON string.

Parsing JSON

Parsing the json data in Javascript means converting json data to an object. JSON.parse() method is an inbuilt JavaScript method that converts text into a JavaScript object.

JavaScript functions are not allowed in JSON. If you want to include a function, write it as a string.

// app.js

let jsonString = '{ "ramsey":"John", "yawuz":30, "appo":"New York"}'
let obj = JSON.parse(jsonString);
console.log(obj)

Output

{ ramsey: 'John', yawuz: 30, appo: 'New York' }

The output here is a js object.

That is it for Converting Javascript json to string.

See also

Javascript Array to Json

Javascript Object toString()

Javascript Object is()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.