Write Data as JSON Text

Dana Reyes keeps her home budget in a JavaScript file. Her October expenses sit in an array of records typed straight into the code. Every new expense means editing the program, and nothing it works out survives once it ends. To keep her data in a file that outlives the program, she first has to turn the records into a format a file can store. This course uses a text format called JSON.

In this lesson, you’ll turn Dana’s records into text with JavaScript’s built-in tools and read that text back into data. You’ll also be able to predict what the text looks like and which values change or vanish on the way. You’ll type along in a script and in the Node.js REPL. Start with the records themselves and the text they become.

Turn Records Into JSON Text

A program can’t write an array of objects to a file as it is. It needs to convert the data into a format that another program, or the same program next week, can read back. JSON, short for JavaScript Object Notation, is that text format. It borrows the look of JavaScript’s arrays and object literals. Almost every programming language can read it.

Create a file called expenses.js with three of Dana’s records. Her real list has about eight, but three are enough to see the format. Each date comes from a call like new Date("2026-10-03"), which builds a Date object for that day, and that’s all you need to know about dates for now:

Language: JavaScript Filename: expenses.js
const expenses = [
  {
    date: new Date("2026-10-03"), category: "groceries",
    amount: 64, note: "farmers market",
  },
  {
    date: new Date("2026-10-05"), category: "transport",
    amount: 45, note: "bus pass",
  },
  {
    date: new Date("2026-10-09"), category: "utilities",
    amount: 72, note: undefined,
  },
];

const text = JSON.stringify(expenses, null, 2);
console.log(text);

The JSON object holds JavaScript’s JSON tools. JSON.stringify() takes a value like Dana’s array and returns its JSON text as one string. The second argument is for a function that can change values on the way. You don’t need one here, so null fills the slot. The third, 2, indents each level by two spaces so the text is readable. Without it, the whole array comes out on one long line.

Run the script, and JavaScript prints the text:

Language: Shell
$ node expenses.js
[
  {
    "date": "2026-10-03T00:00:00.000Z",
    "category": "groceries",
    "amount": 64,
    "note": "farmers market"
  },
  {
    "date": "2026-10-05T00:00:00.000Z",
    "category": "transport",
    "amount": 45,
    "note": "bus pass"
  },
  {
    "date": "2026-10-09T00:00:00.000Z",
    "category": "utilities",
    "amount": 72
  }
]

Every key is now in double quotes, and so is every string, while the numbers stay bare. Two other things changed, though. Each date is now a string, and the third record has no note line at all. Keep both in mind, because the last section of this lesson explains them.

Read JSON Text Back With JSON.parse()

Text in a file only helps Dana if her program can turn it back into records it can work with. JSON.parse() reads JSON text and builds new arrays and objects from it. In expenses.js, replace the console.log(text); line with these lines:

Language: JavaScript
const restored = JSON.parse(text);
console.log("Records:", restored.length);
console.log("Second:", restored[1].category, restored[1].amount);
console.log("Same object?", restored[1] === expenses[1]);

Your file should now build the text and parse it back:

Language: JavaScript Filename: expenses.js
const expenses = [
  {
    date: new Date("2026-10-03"), category: "groceries",
    amount: 64, note: "farmers market",
  },
  {
    date: new Date("2026-10-05"), category: "transport",
    amount: 45, note: "bus pass",
  },
  {
    date: new Date("2026-10-09"), category: "utilities",
    amount: 72, note: undefined,
  },
];

const text = JSON.stringify(expenses, null, 2);
const restored = JSON.parse(text);
console.log("Records:", restored.length);
console.log("Second:", restored[1].category, restored[1].amount);
console.log("Same object?", restored[1] === expenses[1]);

Run it again, and the text comes back as data:

Language: Shell
$ node expenses.js
Records: 3
Second: transport 45
Same object? false

The parsed records work as usual, but the last line shows that restored[1] is a different object from expenses[1], even though it holds the same category and amount. Parsing builds brand-new objects from the text, so changing restored never touches expenses.

text and restored hold the same expenses, yet they’re different kinds of value. When you select the button below, a chat with RealJS’s mentor opens with this question typed in. Send it, then explain the difference in your own words, and the mentor will tell you what you’ve missed:

The text can be parsed only because it follows JSON’s rules, which are stricter than JavaScript’s. Every key and every string needs double quotes. There’s no trailing comma after the last item, and there are no comments.

A value can only be a string, a number, true, false, null, an array, or an object, so neither undefined nor functions are allowed.

Watch out: JSON looks like an object literal, but it isn’t one, so text with single quotes, unquoted keys, or a trailing comma makes JSON.parse() throw a SyntaxError.

See What Changes on the Way

JSON’s short list of value types explains the two surprises in Dana’s text. Values that aren’t on the list get converted or dropped without an error, so learn the rules before Dana’s data goes into a file. A few values can’t be written at all and make JSON.stringify() throw a TypeError, but Dana’s records have none.

A Date isn’t on the list, but it can describe itself as text. JSON.stringify() calls its .toJSON() method, which returns the same moment as a string in a standard format. In that string, T00:00:00.000Z means midnight in Coordinated Universal Time (UTC).

The value undefined isn’t on the list either, so JSON.stringify() leaves out any property that holds it. That’s why the third record lost its note. JSON.stringify() also leaves out properties whose values are functions. On its own, though, undefined or a function makes JSON.stringify() return undefined, not a string.

Values inside an array follow a different rule, and a Map has a rule of its own. Try these lines in the Node.js REPL, which you start by typing node on its own in your terminal:

Language: JavaScript
> JSON.stringify(new Date("2026-10-03"))
'"2026-10-03T00:00:00.000Z"'
> JSON.stringify([64, undefined, NaN])
'[64,null,null]'
> JSON.stringify(new Map([["fun", 150]]))
'{}'

The first line shows a date’s JSON text, which is a string inside the string. In the array, undefined becomes null, and so would a function. Dropping the item would shift every later item to a new index, so null keeps its place. JSON has no NaN, so it becomes null anywhere.

As you may have seen, a Map’s entries aren’t properties, and JSON.stringify() writes only an object’s properties. So a Map comes out as an empty object, and its entries are gone. To save one, convert it to a plain object with Object.fromEntries() first.

Parsing gives back only what the text holds. A date comes back as a string, not a Date, and a dropped note doesn’t come back at all. JSON has no way to say “this string was a date,” so the text alone can’t tell JSON.parse() to rebuild one.

These rules blur together when you meet them one at a time, so try them side by side. Below is one of Dana’s records with a different value in its note field each time, starting with the Date you’ve already seen. As you click through the values, compare the two lines for each one, then check the verdict under them: Kept, Changed, or Dropped.

Interactive diagram — enable JavaScript to view.

The verdicts sort the values three ways. A string and a number are kept. A Date, a Map, NaN, and undefined inside an array are changed, into a string, {}, null, and null. A property set to undefined or a function is dropped from both lines.

Only strings, finite numbers, Booleans, null, and arrays and plain objects made of them survive the trip unchanged. Everything else, including NaN, is converted or dropped, and parsing never rebuilds the original.

Want to test your sense of what survives the trip to JSON?

Check Your Understanding

Predict the first answer and explain the other two before you open the answers below:

  1. Dana stringifies { date: new Date("2026-10-20"), note: undefined } and parses the text back. What does the parsed object hold?
  2. Why does JSON.stringify([45, undefined]) return [45,null] instead of dropping undefined?
  3. Why does JSON.parse() throw a SyntaxError on Dana’s hand-typed { "category": "rent", "amount": 1200, }, and what fixes it?
  1. { date: '2026-10-20T00:00:00.000Z' }: date is a string, not a Date, and note is gone, because it was never in the text.
  2. Dropping an array item would shift every later item to a new index, so undefined becomes null and keeps its place.
  3. JSON allows no comma after the last property. Removing the comma before the } fixes it.

You can now write Dana’s expenses as JSON text and read them back, and you know which values change or vanish on the way. Next, in Save and Load the Expenses File, you’ll put that text in a file, so Dana’s data outlives the program.

Become a Member to join the conversation.