Javascript Object To String Tutorial

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

Written by: Alexandra Anderson

Alexandra Anderson

Alexandra is a web marketer, Agile Product Owner, and die-hard wordsmith who's contributed to HostingAdvice, InMotion Hosting, HostGator, and other prominent hosting and technology blogs, as well as Forbes. She has a master's degree in information technology from Virginia Tech and more than 10 years of experience building websites, advising on web and mobile app design, and crafting content that engages and converts. Her primary subject matter expertise spans WordPress, UX design, Agile project management, and, of course, web hosting.

See full bio »

Edited by: Lillian Castro

Lillian Castro

Lillian brings more than 30 years of editing and journalism experience to our team. She has written and edited for major news organizations, including The Atlanta Journal-Constitution and the New York Times, and she previously served as an adjunct instructor at the University of Florida. Today, she edits HostingAdvice content for clarity, accuracy, and reader engagement.

See full bio »

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

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

JSON.stringify(value)

The full syntax is:

JSON.stringify(value[, replacer[, space]])

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.

JSON.stringify("foo bar"); // ""foo bar""  JSON.stringify(["foo", "bar"]); // "["foo","bar"]"  JSON.stringify({}); // '{}'  JSON.stringify({'foo':true, 'baz':false}); // "{"foo":true,"baz":false}"

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:

var obj = {name: "foo", id: 1, age: 45};  JSON.stringify(obj, ['name', 'id']);   // outputs: {"name":"foo","id":1}"

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

function replacer(key, value) {    if (key === "age") {      return value + ' years';    }    return value;  }//end replacer    var obj = {name: "foo", id: 1, age: 45};  JSON.stringify(obj, replacer);   // outputs: "{"name":"foo","id":1,"age":"45 years"}"

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

JSON.stringify( { 'foo':1, 'bar':2, 'baz':{ 'quux':3 } }, null, 't');

This will output:

"{          "foo": 1,          "bar": 2,          "baz": {                  "quux": 3          }  }"

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:

JSON.stringify( { 'foo':1, 'bar':2, 'baz':{ 'quux':3 } }, null, 2);

The output:

"{    "foo": 1,    "bar": 2,    "baz": {      "quux": 3    }  }"

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.

Advertiser Disclosure

HostingAdvice.com is a free online resource that offers valuable content and comparison services to users. To keep this resource 100% free, we receive compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). HostingAdvice.com does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.

Our Editorial Review Policy

Our site is committed to publishing independent, accurate content guided by strict editorial guidelines. Before articles and reviews are published on our site, they undergo a thorough review process performed by a team of independent editors and subject-matter experts to ensure the content’s accuracy, timeliness, and impartiality. Our editorial team is separate and independent of our site’s advertisers, and the opinions they express on our site are their own. To read more about our team members and their editorial backgrounds, please visit our site’s About page.

ABOUT THE AUTHOR

Alexandra Anderson’s interest in website administration was sparked in her teens, priming her for a fast-paced career in managing, building, and contributing to online brands, including HostingAdvice, Forbes, and the blogs of prominent hosting providers. She brings firsthand experience reviewing web hosts, perfecting website design, optimizing content, and walking site owners through the steps that add up to a successful online presence. With a master's degree in information technology from Virginia Tech, she combines her extensive writing experience and technical understanding to unpack some of the most complex topics that daunt novice website owners, as well as the subjects that excite veteran technologists within the HostingAdvice readership.

« BACK TO: HOW-TO
Follow the Experts
We Know Hosting

$

4

8

,

2

8

3

spent annually on web hosting!

Hosting How-To Guides