JSON to string JavaScript | Example code

  • by

Use the JSON stringify() method to convert JSON to string JavaScript. This converts a JavaScript object or value to a JSON string.

JSON to string JavaScript

Simple example code easily converts a JavaScript object into a JSON string.

<!DOCTYPE html>
<html>
<body>

  <script>

    var obj = {name: "Martin", age: 30, country: "United States"};
    console.log(obj);

    var json = JSON.stringify(obj);
    console.log(json);

  </script>

</body>
</html> 

Output:

JSON to string JavaScript

All values in JSON to string in JS

One option would be to exploit the naturally recursive nature of JSON.stringify, and use the reviver function to convert all non-object (and non-null) values to strings:

const input = {
  "obj1": [{
      "n1": "n",
      "n2": 1,
      "n3": true
    },
    {
      "n1": "n",
      "n2": 1,
      "n3": null
    }
  ]
};
const json = JSON.stringify(input);
const withStrings = JSON.parse(json, (key, val) => (
  typeof val !== 'object' && val !== null ? String(val) : val
));
console.log(withStrings);

Output:


{
  "obj1": [
    {
      "n1": "n",
      "n2": "1",
      "n3": "true"
    },
    {
      "n1": "n",
      "n2": "1",
      "n3": null
    }
  ]
}

Or You could take JSON.stringify with a replacer function and check if the value is a number, then take a stringed value or just the value.

var object = { obj1: [{ n1: "n", n2: 1, n3: true }, { n1: "n", n2: 1, n3: null }] },
    json = JSON.stringify(object, (k, v) => v && typeof v === 'object' ? v : '' + v);

console.log(json);
console.log(JSON.parse(json));

Do comment if you have any doubts or suggestions on this JS JSON 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.