Learn how JSON.stringify converts JavaScript values and objects into JSON text for HTTP requests or local storage. See how its formatting and property-filtering options help shape data, and how JSON.parse can turn that text back into usable JavaScript—handy when data needs to travel between systems.

Multiple Choice

What does JSON.stringify do?

The function JSON.stringify is used to convert JavaScript objects or values into a JSON string format. This is essential for cases where data needs to be transmitted, such as between a client and a server, or when storing data in a format that can be easily parsed later. For example, when you have a JavaScript object that represents a user's profile, using JSON.stringify will convert that object into a JSON string that can then be sent over an HTTP request or saved into local storage. This transformation is crucial because it allows for the preservation of the object's structure in a way that is universally readable and can be used across different programming environments. Generating a JSON string from a JavaScript object helps ensure that the data is structured correctly and can be easily reconstructed back to the original object state using JSON.parse. Additionally, JSON.stringify offers options to control the output format, such as indentation or removing certain properties, enhancing its utility in data management and communication.

JSON.stringify in JavaScript: Turning Data into a Shareable Format

JavaScript objects are handy because they let code group related information under clear names. A Salesforce app might hold a contact’s name, email address, and account details in one object. But when that data needs to travel to a server or be saved as text, the object itself isn’t always the right format. That’s where JSON.stringify() comes in: it converts a JavaScript value into a JSON string.

Think of it as packing a set of labeled items into a box that other systems can understand. The labels and structure remain visible, but the result is now text—a form that can be sent, stored, or read later.

From JavaScript value to JSON text

Here’s a simple example:


const contact = {

firstName: "Maya",

lastName: "Chen",

email: "maya.chen@example.com"

};

const jsonText = JSON.stringify(contact);

console.log(jsonText);

The resulting string looks like this:


{"firstName":"Maya","lastName":"Chen","email":"maya.chen@example.com"}

The object has become a string containing JSON-formatted text. That distinction matters. Before conversion, contact is a JavaScript object, so code can access a property with contact.firstName. After conversion, jsonText is a string. It can be sent in an HTTP request body or stored in a text-based location, but code can’t access its fields as object properties until it turns the text back into a value.

JSON stands for JavaScript Object Notation. Despite the name, it isn’t limited to JavaScript. It’s a widely used text format that lets systems built with different languages exchange structured data. A Salesforce interface, a JavaScript service, and a server written in another language can all work with JSON, provided they agree on the structure.

Why Salesforce developers use it

Salesforce developers often move data between a browser, Salesforce services, and external systems. A Lightning Web Component might gather a few values from a user, then send them to an Apex method or a web service. JSON can provide a clear, familiar structure for that exchange.

For instance, an app might create a small payload like this:


const requestData = {

recordId: "003000000000001AAA",

updates: {

title: "Customer Success Manager",

department: "Support"

}

};

const body = JSON.stringify(requestData);

The body variable is now a string representation of the data. In code that sends an HTTP request, it can be supplied as the request body:


fetch("/services/data/example", {

method: "POST",

headers: {

"Content-Type": "application/json"

},

body: JSON.stringify(requestData)

});

The Content-Type header tells the receiving service what kind of text to expect. The conversion itself doesn’t send anything; it only creates the string. That’s an easy detail to miss. JSON.stringify() prepares data, while fetch() or another networking tool handles the actual communication.

The same idea applies to browser storage. Storage APIs generally save strings, so an object can be converted before it’s stored:


localStorage.setItem("contactSettings", JSON.stringify({

showEmail: true,

theme: "light"

}));

Later, the stored text can be converted back into a JavaScript value with JSON.parse():


const savedText = localStorage.getItem("contactSettings");

const settings = JSON.parse(savedText);

So the two methods work as a pair: JSON.stringify() turns a value into JSON text, and JSON.parse() reads JSON text and creates a JavaScript value. One packs the data; the other opens the package.

What gets included—and what doesn’t?

For common data types, JSON.stringify() behaves in a predictable way. It can handle objects, arrays, strings, numbers, booleans, and null.


JSON.stringify(["North", "South"]);

// '["North","South"]'

JSON.stringify(true);

// "true"

JSON.stringify(null);

// "null"

A few JavaScript values don’t map neatly to JSON. For example, JSON has no undefined value, no function type, and no symbol type. When these appear as object property values, they’re generally left out:


const profile = {

name: "Maya",

nickname: undefined,

greet: function () {

return "Hello";

}

};

JSON.stringify(profile);

// '{"name":"Maya"}'

That can affect data without throwing an obvious error. If a field is missing from the resulting string, it may be because its value couldn’t be represented in JSON—not because stringify() erased the whole object.

Arrays behave a little differently. An unsupported value in an array is represented as null:


JSON.stringify([1, undefined, 3]);

// "[1,null,3]"

This difference is worth remembering when shaping data for a service. If a value must be sent, make sure it has a JSON-compatible form, such as a string, number, boolean, array, object, or null.

There are other limits, too. Circular references—where an object eventually points back to itself—can’t be represented in ordinary JSON. Trying to stringify one causes an error. Dates are usually converted to strings, while objects such as Map and Set may need to be converted manually if their contents should appear in the output.

Formatting and choosing properties

By default, JSON output is compact. That’s useful for sending data, but it can be hard to read while debugging. The third argument to JSON.stringify() can add indentation:


const readableJson = JSON.stringify(requestData, null, 2);

console.log(readableJson);

The 2 asks JavaScript to indent nested levels by two spaces. The result is easier to scan, much like a neatly arranged set of shelves instead of a pile of boxes. This format is often helpful in logs or local files, though compact output is usually fine for network requests.

The second argument, called a replacer, gives more control over what appears. It can be an array of property names:


const publicContact = JSON.stringify(contact, ["firstName", "email"]);

That output includes only the listed properties. Or a replacer function can adjust values as they’re converted:


const jsonText = JSON.stringify(contact, (key, value) => {

if (key === "email") {

return value.toLowerCase();

}

return value;

});

This feature can be useful, but it deserves care. Filtering out a field from JSON doesn’t change the original object; it only changes the string being produced. And if sensitive information should never leave the browser, it’s safer not to place it in the object being sent at all. Data handling is easier to reason about when the payload starts with only the fields the receiving system needs.

A few useful habits

When working with JSON.stringify() in Salesforce JavaScript, keep the data shape simple and intentional. Build a payload for the task rather than serializing a large UI object with extra state, methods, or unrelated values. This keeps requests easier to inspect and reduces the chance of sending fields that don’t belong in an integration.

Also remember that the result is a string. If an API expects JSON, send the string with an appropriate content type. If code later needs to inspect the data, parse it first. And if serialization fails, check for circular references or values that need special handling.

At its core, JSON.stringify() does one focused job: it converts JavaScript objects and other supported values into JSON text. That small step makes structured data portable. In a Salesforce application, it can help a component save settings, send a request, or pass information to another system—without changing the original object itself.