Skip to content

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.stringify(value, replacer, space);

The value parameter represents the JSON object you want to convert to a string.

The replacer parameter is optional. It can be a function or an array that specifies how values should be transformed before being included in the final JSON string. If you don’t need any transformations, you can omit this parameter or pass null.

The space parameter is also optional. It specifies the indentation level for formatting the output string. It can be a number representing the number of spaces to use for indentation, or a string (e.g., ‘\t’) for tab indentation. If you don’t need any formatting, you can omit this parameter or pass null.

Note: JSON.stringify() converts the object to a JSON string, including all the key-value pairs and their corresponding values.

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. Required fields are marked *