JSON is a lightweight data-interchange format. It is used to transmit data between a server and a client.
You can use JSON.Stringify() method to convert a JS object to a JSON string as shown below.
eval is used to convert
eval as it will evaluate the mathematical expressions.
There is no space appended at the JSON properties’ beginning. You’ll see how to add space and indentation in the next section.
You can assign the JSON value to a text element using the
.value property of the element.
text_element_id.value = JSON.stringify(obj);
This is how you can convert the object to JSON String using the
The JSON stringify method supports additional parameters to support the pretty printing of the JSON string.
The stringify method parameters are
value– Object to convert to a json string
replacer– A replacer method to replace specific characters during the conversion. An optional parameter. You must pass the
Nullvalue if you want to use the space for pretty printing
space– Number of spaces to insert into the beginning of each JSON object property—an optional Parameter. The maximum acceptable number is 10. If you pass a value of more than 10, it will be considered 10
The above code will include seven spaces in the string to prettify it, and the JSON will look like the following.
- Each object is of a different type, and the objects will have a set of properties.
- You can access these properties using the
JSON Strings are strings used for storing and transporting data.
- You can use JSON in any language such as
JSON.stringify escaping without need
Stringify() method, additional escape characters are appended to it.
For example, add the following JSON string in a text box.
Try to convert it into a JSON string using
You’ll see the following output with escape characters.
Hence, you need to be careful to pass a JSON object to a
Stringify() method instead of passing JSON Strings.
JS Object to JSON String without Stringify
JSON.Stringify() is the recommended method to convert js Object to JSON String.
Stringify(), define a user-defined method as available in this StackOverflow answer.
Be aware that this doesn’t handle the undefined values for any JSON property. Using this type of method will consider
undefined as a