JSON: parse and stringify, and why JSON.parse returns any
Turn a value into JSON text with JSON.stringify and back with JSON.parse, and see why JSON.parse returns any: TypeScript checks before the text exists, so a typo slips through until you write the type on the box. Learn JSON’s strict rules, why a Map becomes {}, what a SyntaxError from JSON.parse means, and give TaskKit tasksToJson and tasksFromJson.
Fundamentals
TypeScript
JSON: `parse` and `stringify`, and why `JSON.parse` returns `any`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Add two tasks to TaskKit, and it lists them:
#1 [todo] Buy milk, due: not set and
#2 [todo] Call Mom, due: not set. Run npm start help a minute
later (npm, the Node package manager, runs TaskKit's start script),
and TaskKit says 0 tasks added, room for 5 more, with nothing under
Your list, A to Z:. Nothing is broken. TaskKit keeps its tasks in a
Map, in memory, and as lesson 1.1 said, the boxes in memory are
emptied when a program ends. Every run starts from nothing.
To keep its tasks, TaskKit has to put them somewhere that outlasts
the run: a file, which is the next lesson. But a file holds text, and
a task is an object. Think of a wardrobe that arrives flat-packed:
taken apart into a flat box that travels well, and built again from
its parts at the other end. In this lesson you learn JSON (JavaScript
Object Notation), the flat pack that programs use. You turn TaskKit's
tasks into text and back, see why TypeScript cannot vouch for what
comes back, and learn what to write so that it keeps checking.
Objects live in memory, text travels
Inside your program, a task has properties your code reads as
task.title. Outside it, in a file or on a website, there are no
boxes and no objects, only text: characters, one after another.
So a value that leaves your program is written out as text, and text
that comes in is built back into a value.
JSON is the agreed way to write a value as text. You met it in Module 9 as
the format of package.json and tsconfig.json: names in double quotes, a
colon, the value, commas in between. It is the way JavaScript writes objects,
made strict, and almost every program and website can read it. JavaScript
comes with a ready-made object, also called JSON, with one method for each
direction: JSON.stringify writes a value out as text, and
JSON.parse builds a value from text. Press Next step to follow one
task out and back, or let it play:
task: an object
{ id: 1, title: "Buy milk", status: "todo" } in a box in your
program's memory. It is gone when Node ends.
JSON.stringify(task)
Writes the object out as one string of characters, in the JSON
format.
text: a string
{"id":1,"title":"Buy milk","status":"todo"}. Plain text, which a
file or a website can keep after Node ends.
JSON.parse(text)
The edge of your program: text from a file or a website comes back
in, and a new object is built from it.
back in: any
The same three properties again, but TypeScript never saw the text,
so it types the object any.
Out as text, back in as an object that TypeScript knows
nothing about
All 5 steps shown.Step 1 of 5: task: an objectStep 2 of 5: JSON.stringify(task)Step 3 of 5: text: a stringStep 4 of 5: JSON.parse(text)Step 5 of 5: back in: any
All 5 steps shown.
The last step is the one this lesson is about. First, the two trips
themselves.
JSON.stringify: from a value to text
Stringify means "make into a string". Hand JSON.stringify a
value, and it gives back a string that describes it. Press Run:
It prints {"id":1,"title":"Buy milk","status":"todo"}, and then
string: text is not an object any more, only characters. Look at
how JSON writes them:
every name in double quotes: "title", never title;
every string in double quotes too: "Buy milk";
numbers, true and false as they are: 1;
an array in square brackets, its items separated by commas;
no comma after the last item or property: TypeScript allows one,
JSON does not;
a property that holds undefined is left out. JSON has null,
which it keeps, but no undefined.
On one line with no spaces, JSON is easy for a program to read and
hard for you. Two more arguments ask for a version a person can read:
The 2 asks for two spaces of indent on every level, with each
property on a line of its own. The second argument can pick which
properties to write. This course never needs it, so null holds its
place. The array comes out between [ and ], each task between {
and }.
JSON.parse: from text back to a value
Parse means read a text and work out how it is built. JSON.parse
reads JSON text and builds the value it describes:
Line 1 puts the JSON text in single quotes, which lesson 2.2 said a string may
use; they leave the double quotes of JSON inside it alone. Press Run: it
prints Buy milk, then 2. task is an object again, with real properties,
and task.id is the number 1, not the character 1.
JSON.parse is strict: text that is not JSON stops it, as the common
mistake below shows.
Why JSON.parse returns any
In VS Code (Visual Studio Code, your editor), make a file load.ts in
taskkit, paste the four lines above into it, and rest the pointer on
task: the hover says const task: any. TypeScript does
not know what task holds, and the reason is time. TypeScript checks
your files before they run. The text JSON.parse reads usually comes
from outside, from a file someone edited or from a website, and it
exists only once the program runs. JSON.parse is written once, for
every text anyone will ever hand it, so all its type can promise is
"some value". Even when the text sits on line 1, as here, TypeScript
does not read it as JSON to work out what it holds. Like the flat pack,
the text does not say what is inside.
"Some value, I do not know which" is unknown in lesson 8.5, the safe
box. But the type of JSON.parse was written before TypeScript had
unknown, and, like .catch in lesson 11.6, it keeps the older
any so that existing code still passes the check. That is the same
hole you closed in .catch, and you close it the same way: by
writing the type yourself.
Lesson 8.5 showed what any does: every use of it passes the check,
and so does every property you read from it. So a typo in a
property's name goes straight through to Node, unless you write the
type of the value on the box. In the figure, "save" is you saving the
file, and TS2551 is TypeScript's (TS) number for the error. Switch
between the two types, press Next step to walk through one, or let
it play:
Bad — back is any, so the typo
passes the check and Node prints undefined.
Good — the box says Task, so the
check stops the typo before anything runs.
Run both. The second block writes Task out at the top because the
page has no tasks.ts to import it from, so its typo is on line 9.
In a real program the undefined of the first version would land in
a list or a file, and you would find it long after, far from the line
that caused it.
TypeScript accepts const back: Task = JSON.parse(text); because an
any fits into a box of any type. So the type you write is a
promise, and TypeScript holds every later line to it, but it never
looks at the text itself. Lesson 8.5 said to write unknown where
you cannot know what a value holds. Here you can: for text your own
program wrote with JSON.stringify, you know what went in, and the
promise is safe. For text from anywhere else, unknown and a check
are the answer, and lesson 12.5 builds that.
Predict before you run
This task has a due property, but nothing is in it yet.
Predict
What does this program print?
The common mistake: names without quotes
JSON looks so much like the objects you write in TypeScript that it
is easy to write it the TypeScript way, with names left bare.
Common mistake
Names without double quotes in JSON text
You write a task as JSON text by hand, the way you would write the
object, and save it as load.ts in taskkit:
npm run check finds nothing wrong: to TypeScript, line 1 is a
string like any other. node load.ts stops on line 2, because
JSON.parse meets id where JSON needs a " to start a name.
SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)
The fix
Put every name in double quotes:
It prints Call Mom. When JSON.parse throws a SyntaxError, the error for
text that breaks the rules of its format, read its column: it counts
characters from the left, so column 3 is the i of id, the first character
that is not JSON. (The position says the same, counted from 0, as array
indexes are.) Look there for a bare name, single quotes, or a comma after the
last item. Text you did not write can be broken in the same way, and since
JSON.parse throws, a try / catch (lesson 8.3) around it can catch it.
If you saved a load.ts in taskkit while reading this lesson,
delete it now: it is not part of TaskKit, and npm run check keeps
checking it.
TaskKit: tasks to text and back
TaskKit's tasks are in tasks, a Map<string, Task> in index.ts.
Before the next lesson can save them, they need a way to become text
and a way back.
1
See what a Map turns into
In ~/projects/taskkit/index.ts, add this line at the very end of the
file, after the catch:
Run TaskKit with two tasks:
The last lines are:
The line you added prints only {}. JSON writes out the
properties an object holds itself, and a Map keeps its entries in a
place JSON does not look, so the tasks are lost on the way. Turn the
values into an array first, [...tasks.values()], as printList
already does (lesson 10.1). Delete the line again.
2
Write tasksToJson and tasksFromJson
At the end of tasks.ts, add two functions:
tasksToJson writes the tasks as an indented JSON array.
tasksFromJson builds the array back. Its return type, Task[], is
the promise from earlier in this lesson, safe for the same reason:
the text will be the one tasksToJson wrote.
3
Test the way out and back
In tasks.test.ts, add the two names to the first line that imports
from ./tasks.ts, the one with capitalize; leave the import type
line under it as it is. With six names the line gets too long, so
write one name per line, between the braces:
Then add a test at the end of the file:
Check and test:
The check prints only its two > lines. The tests end with
ℹ pass 11 and ℹ fail 0: the two tasks went out as text and came
back, in order.
4
See TaskKit's tasks as JSON
In index.ts, add tasksToJson to the line that imports
capitalize:
and at the very end of the file, this line:
Run npm start add "buy milk" "call Mom" again. These are the last
lines it prints:
That text is what the next lesson saves. TaskKit should not print it
on every run, so delete the line and take
out of the import again.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. Press Check when you think
you have it; the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What does JSON.stringify(task) give back?
Check yourself
Why does JSON.parse return any?
Check yourself
What does JSON.stringify give for a Map of tasks?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
JSON: parse and stringify
What things are
Word
What it means
JSON
A value written as text: names and strings in double quotes
JSON
The built-in object with stringify and parse
Text
What files and websites hold: characters, not objects
Code
Write
To
JSON.stringify(task)
Write a value out as JSON text
JSON.stringify(tasks, null, 2)
Write it indented, for a person
JSON.parse(text)
Build a value from JSON text; its type is any
const back: Task = …
Keep checking what JSON.parse gives back
Rules
Rule
What it means
No comma after the last item
TypeScript allows one; JSON does not
undefined is left out
A property that holds it is not written
A Map becomes {}
Write [...tasks.values()] instead
Bad JSON throws
A SyntaxError names the first wrong column
any lets typos through
Write the type on the box that holds the value
A written type is a promise
The check trusts it and never reads the text
Where to go next
You can now write a value out as JSON text with JSON.stringify,
build it back with JSON.parse, and keep TypeScript checking by
writing the type on the box. You know why that type is any to begin
with, why a Map comes out as {}, and what a SyntaxError from
JSON.parse is telling you. TaskKit can turn its tasks into text and
back.
Next is Reading and writing files: readFile and writeFile,
where TaskKit writes the text
from tasksToJson to a file and reads it back on the next run, so its
tasks finally outlast Node.
Before you move on, go back to the Predict's code, press Edit,
change due: undefined to due: "Friday", and predict the output
before you press Run.
You
TypeScript
Node
You: savesavesave
TypeScript: checked ✓checked✓checked✓
Node: parseparseparse
Node: undefinedundefinedundefined
Time
back holds what JSON.parse(text) gives back, and the next line
reads back.titel.
back is any, so every use of it passes, titel included.
Only now is the text read, and an object built from it.
The object has no titel, so the program prints undefined. No
error, anywhere.
With any, Node finds the typo by printing undefined; with
Task, TypeScript finds it first
All 4 steps shown.Step 1 of 4: You: saveStep 2 of 4: TypeScript: checked ✓Step 3 of 4: Node: parseStep 4 of 4: Node: undefined
All 4 steps shown.
You
TypeScript
Node
You: savesavesave
TypeScript: TS2551TS2551TS2551
Node: never startsneverstartsneverstarts
Time
The box is now const back: Task = JSON.parse(text);, and the
next line is the same.
Property 'titel' does not exist on type 'Task'. Did you mean 'title'? Nothing has run.
The check failed, so nothing runs until you fix the typo.
With any, Node finds the typo by printing undefined; with
Task, TypeScript finds it first
All 3 steps shown.Step 1 of 3: You: saveStep 2 of 3: TypeScript: TS2551Step 3 of 3: Node: never starts
All 3 steps shown.
console.log
tasksToJson
Exercise · Read the code
Which text is JSON
Which of these texts can JSON.parse read without throwing?
Exercise · Predict the result
The type after the box says Task
In VS Code, which type does the hover show for title on line 8?
import { capitalize, tasksToJson } from "./tasks.ts";
index.tsts
console.log(tasksToJson(tasks));
Exercise · Fix the error
Read the title from the object
text holds a task as JSON. The program should print its title,
Water plants, but the check refuses line 2. Fix it so that it
prints the title, read from the text.
Loading the editor…
Exercise · Write the code
Load, change and write a list
text holds two tasks as a JSON array, too long for one line, so it
is written as two strings joined with +. Build the tasks into a box
tasks of type Task[], mark the first task "done", and print the
whole list as JSON, indented by two spaces. That is the trip out and
back that TaskKit will make with its file.