JavaScript object to JSON string | Example code

  • by

Use JSON.stringify() method to convert JavaScript object to JSON String. This method is supported by all browsers that have native JSON support built-in.

The conversion is a String to Object

JSON.stringify({"key":"value"});

to make it a JSON String following could be used.

var x = {
  "name": "John"
};
console.log(JSON.stringify(x));

JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

Example convert object to JSON string in JavaScript

Simple example code Convert JS object to JSON string.

<!DOCTYPE html>
<html>
<head>

  <script>

    var obj = {name: "Martin", age: 30, country: "United States"};

    var json = JSON.stringify(obj);

    console.log(json);
    console.log(typeof(json))

  </script>

</head>
</html>

Output:

JavaScript object to JSON string

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

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