javascript · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
turns objects into text, and back again.
Programs send each other data as plain text. JSON is the most common way to write it. It looks almost exactly like JavaScript objects and arrays, except that every key and every string sits in double quotes.
turns an object into JSON text, ready to send or save. does the opposite: it reads JSON text and builds a real object, so you can use dots again.
Text in, object out. Badly written JSON makes JSON.parse crash with a SyntaxError.
const pet = { name: "Rex", age: 3 };
const text = JSON.stringify(pet);
console.log(text, typeof text);
const reply = '{"name":"Tibbles","age":7,"toys":["mouse","string"]}';
const cat = JSON.parse(reply);
console.log(cat.name, cat.toys[1]); Single quotes make a string too, which is handy when the text is full of double quotes.
guess first
Text first, then an object. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const text = '{"title":"Moana","songs":12}';
console.log(typeof text);
const film = JSON.parse(text);
console.log(film.songs + 1, typeof film);
your turn
Your turn. Save a game and load it back.
Pick a player name and a level number. Then fill in the method that turns JSON text back into an object. Press run.
fix it
The weather reply will not parse. Fix it!
JSON.parsecrashes with a SyntaxError, so the text on line 1 is not proper JSON.- JSON is strict: keys and strings must sit in double quotes, never single ones.
- Swap the quote marks on line 1, single on the outside and double inside, then press run.
nailed it
you turned data into text and back. :D
- JSON is data written as text, with double quotes everywhere.
JSON.stringifyturns an object into JSON text.JSON.parseturns JSON text back into an object.
new words in your collection
- JSON
- stringify
- parse
This lesson isn’t saved. A free account remembers every lesson you finish.