Learn by reading through in order

JSON — stringify and parse

Turn objects into strings with JSON.stringify and back with JSON.parse, plus indenting and the values lost in between.

Try to save settings or a cart's contents in the browser, or send them to a server, and you can't hand over the object as it is — only a string can be saved or sent.

Convert it to JSON (a data format for representing key-value pairs as a string), and you can save it directly — and whoever receives it can turn it back into the original object. This article covers JSON.stringify, which converts to it, and JSON.parse, which converts back.

Turning an Object into a String — JSON.stringify

To use an object for saving or sending, it first needs to become a string. Stitch one together yourself with something like "{" + key + ":" + value + "}", and it breaks the moment a value contains a quotation mark — so use a function that converts it to a fixed format instead.

Write JSON.stringify(settings), and it converts the object into a single-line string in JSON format. What comes back is a string, so typeof returns "string", and string methods like length and includes work directly on it.

JSON looks a lot like the way you write JavaScript objects, but it isn't the same. Keys must always be wrapped in double quotes, and string values use only double quotes too.

You can't leave a trailing comma, and you can't include comments either. This difference is exactly what causes the SyntaxError covered later.

JavaScript Object Syntax vs JSON
A JavaScriptobjectKeys don'tneed quotes{ theme: "dark" }A JSONstringKeys and valuesboth quoted{"theme":"dark"}A trailingcommaAllowed inJavaScriptNot allowedin JSON
JSON wraps both keys and strings in double quotes, and doesn't allow a trailing comma. It looks similar, but it's a different format.
const product = { name: "Drip Coffee", price: 780, inStock: true };

const productJson = JSON.stringify(product);
console.log(productJson);
// {"name":"Drip Coffee","price":780,"inStock":true}

// What comes back is a string, so string methods work directly
console.log(typeof productJson);            // string
console.log(productJson.includes("price")); // true

// Arrays convert the same way
console.log(JSON.stringify(["Kitchen", "Stationery"]));  // ["Kitchen","Stationery"]

Convert an app's settings into a string that can be saved. settings is already declared.

① Convert settings into a JSON string and print it.

② Print the type of what you got in ①.

③ Print the character count of what you got in ①.

④ Print whether what you got in ① contains the word theme.

(If it runs correctly, an explanation will appear.)

JavaScript / TypeScript Editor

Run code to see output

Making It Readable — Indenting with a Third Argument

A JSON string packed onto one line is fine for sending, but it's hard to read when you want to check the contents yourself. Line breaks and indentation help when you're writing it out as a config file, or checking how things work as you develop.

Pass a number as the 3rd argument, as in JSON.stringify(order, null, 2), and it returns a multi-line string indented by that many spaces. The 2nd argument selects which keys to pull out; pass null to output everything as-is.

Even formatted, what comes back is still a string, so it can be split into lines with split("\n"). "\n" is how a single line break is written.

What Changes With a Third Argument
No 3rdargumentNo linebreaks addedA single-linestring3rd argumentof 2Indented by2 spacesA multi-linestringEither wayNot turned backinto an objecttypeof isstring
Even with indentation, what comes back is still a string. Only the line breaks and spacing change.
const product = { name: "Drip Coffee", price: 780 };

// Pass 2 as the 3rd argument to indent by 2 spaces
const pretty = JSON.stringify(product, null, 2);
console.log(pretty);
// {
//   "name": "Drip Coffee",
//   "price": 780
// }

// Even formatted, what comes back is a string
console.log(typeof pretty);              // string
console.log(pretty.split("\n").length);  // 4

Format an order so it's readable enough to paste straight into a config file. order is already declared.

① Print the character count when it's converted without indentation.

② Convert it to a form indented by 2 spaces, and print it as-is.

③ Print how many lines ②'s result has.

④ Print only the 2nd line of ②'s result.

JavaScript / TypeScript Editor

Run code to see output

Turning a String Back into an Object — JSON.parse

A saved string, or one received from a server, can't be read as-is with something like order.total. To pull out values or run calculations on them, it needs to become an object again.

Write JSON.parse(savedJson), and it reads the JSON string, builds an object from it, and returns that object. Numbers come back as numbers and booleans as booleans, so a calculation like order.total + 1000 just works.

Arrays come back as arrays too, so length counts the entries.

Pass a string that doesn't follow JSON's format, and it throws a SyntaxError, stopping execution on that line. This happens with an extra trailing comma, a key that isn't wrapped in quotes, or a string that's been cut off midway.

The Round Trip, and When It Can't Convert Back
An objectJSON.stringifyA JSONstringA JSONstringJSON.parseAn objectA brokenstringJSON.parseStops with aSyntaxError
stringify turns it into a string, parse turns it back. Anything outside JSON's format stops with a SyntaxError.
const savedJson = '{"name":"Drip Coffee","price":780,"tags":["Kitchen"]}';

const product = JSON.parse(savedJson);
console.log(product.name);           // Drip Coffee

// Numbers come back as numbers, so calculations just work
console.log(product.price * 2);      // 1560

// Arrays come back as arrays
console.log(product.tags.length);    // 1
console.log(typeof product);         // object

// Round-tripping it gives back the same contents
console.log(JSON.stringify(product) === savedJson);  // true

Turn a saved order string back into an object you can work with. savedJson is already declared.

① Turn the string back into an object, and print the order number.

② Print the total with 1000 added to it.

③ Print the number of items.

④ Print the type of what you turned it back into.

JavaScript / TypeScript Editor

Run code to see output

A String You Receive Can Be Broken

If a connection cuts off partway through, or someone hand-edits a config file and leaves a stray comma in, JSON.parse throws a SyntaxError and stops on that line. Once it stops, nothing after it runs at all, so whenever you turn a string from outside back into an object, assume it can fail.

Writing code that keeps going even after a failure is covered in the article on exception handling.

The code provided tries to turn a string with a stray trailing comma back into an object. Run it as-is and check how far it gets and what message stops it.

JavaScript / TypeScript Editor

Run code to see output

What Gets Lost in the Round Trip — undefined and Date

JSON can only represent strings, numbers, booleans, null, arrays, and objects. Convert an object that holds any other kind of value, and that value silently disappears or gets swapped for something else.

That's where the mismatch comes from when you save something and read it back with fewer fields than before.

A property whose value is undefined is dropped, key and all, at conversion time. A property whose value is a function is dropped the same way. An undefined inside an array gets swapped for null instead, to keep its position.

Date (a built-in value representing a date and time; not covered in this course) gets converted into a string. It stays a string after JSON.parse too, and doesn't come back in a form you can use as a date.

If you need to use it as a date afterward, rebuild it yourself with new Date(string).

What Survives the Round Trip
Numbers, strings,booleans, nullWritten outas-isCome back thesame typeAn undefinedpropertyDropped,key and allStill missingafterwardDateWritten outas a stringStays astring
Only what JSON can represent comes back as-is. undefined disappears, and Date comes back as a string.
Original valueAs JSONAfter coming back
String, number, boolean, nullWritten out as-isComes back the same type
An undefined propertyDropped, key and allThe key is missing
A property whose value is a functionDropped, key and allThe key is missing
undefined inside an arraySwapped for nullnull
DateWritten out as a stringStays a string
const record = {
  orderId: "ORD-1477",
  couponCode: undefined,
  orderedAt: new Date("2026-09-02T09:00:00Z"),
  tags: ["Kitchen", undefined],
};

const json = JSON.stringify(record);
console.log(json);
// {"orderId":"ORD-1477","orderedAt":"2026-09-02T09:00:00.000Z","tags":["Kitchen",null]}

const restored = JSON.parse(json);
console.log("couponCode" in restored);   // false (dropped, key and all)
console.log(typeof restored.orderedAt);  // string (doesn't come back as a Date)
console.log(restored.tags[1]);           // null (became null inside the array)
QUIZ

Knowledge Check

Answer each question one by one.

Q1Convert with indentation, as in JSON.stringify(order, null, 2). What's the typeof of what comes back?

Q2What happens when you run JSON.parse('{"total":7400,}')?

Q3Run JSON.stringify on an object with a property whose value is undefined. What happens to that property?