JavaScript "Object to String" Using JSON.stringify()

JavaScript "Object to String" Using <em>JSON.stringify()</em>

While developing a JavaScript application, you will sometimes want to serialize your data into a plain string. This can be useful for things like:

  • Storing object data in a database
  • Outputting object data to the console for debugging
  • Sending object data over AJAX or to an API

The simple syntax for converting an object to a string is:

The full syntax is:

Note: For the purposes of this article, whenever we say “object” we mean “object, array, or value.” We had it the other way around originally, but we quickly realized this became annoying to read.

Examples of Going From an Object to a String

Let’s see some simple examples. Note that the whole string gets double quotes and all the data in the string gets escaped if needed.

This is all pretty straightforward. It’s extremely useful for debugging purposes and for seeing all of the data in your JavaScript objects and arrays. There are two other parameters that can be input into the JSON.stringify() function and we will go over those below. They are great to know about but are used infrequently.

Filtering the Output

For more control over the stringify output, you can pass an array of string or number fields that will act as a selection filter for the stringify output:

You could also define a replacer function to get more control over the resulting string output.

Any other manipulation of the key-value pairs is possible with the replacer function control.

Indent the Output

You’ll often need to indent the stringify output for better readability. You can do so using a number of spaces or a string such as a TAB character. Most times, default indentation will work fine, but if you need to change it, this is how to do so.

Indenting with TAB

Let’s indent the following JSON data with a TAB character: \t

This will output:

We can see that each object depth will get an additional TAB indentation. Note also that the replacer argument is “null” here as we do not use it.

Indenting with Spaces

Let’s indent the same object with four spaces:

The output:

Going From a String to an Object

What if you want to take a string and convert it back into an object or an array?

JSON.parse() parses a string as JSON, so it will take in a string value and output a JSON value. Ergo, it’s the opposite of JSON.stringify().

That’s enough stringification fun for now. Manipulating JSON into your string format is pretty easy to do, but as always, if you’re still stuck, drop us a line below.

Alexandra Leslie

Questions or Comments? Ask Alexandra!

Ask a question and Alexandra will respond to you. We strive to provide the best advice on the net and we are here to help you in any way we can.