AI Hints
Home›JavaScript Tutorial›JSON and Copying
JavaScript · Lesson 64 of 138

JSON

Data as text.

⏱ 2 min read▶ Video at 1:18:15🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

When data travels between computers, from a server to your browser, or into a file, it travels as text. The most popular format for that text is JSON, JavaScript Object Notation. It looks almost exactly like JavaScript objects.

JSON
From the video: JSON
  • Data travels as text
  • Server to browser, files
  • JSON

stringify and parse

JSON dot stringify turns an object into a JSON string. The extra arguments add indentation, to make it readable. JSON dot parse goes the other way, turning a JSON string back into a real object you can use. Run it.

app.jsjavascript
const settings = { theme: "dark", fontSize: 16, tags: ["a", "b"] };

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

const back = JSON.parse(text);
console.log(back.theme, typeof back);
Output
{"theme":"dark","fontSize":16,"tags":["a","b"]} string
{
  "theme": "dark",
  "fontSize": 16,
  "tags": [
    "a",
    "b"
  ]
}
dark object

JSON rules

JSON is stricter than JavaScript. Keys must be in double quotes, strings must use double quotes, and there are no trailing commas or comments. It can't store functions, or undefined. If you try to parse broken JSON, you get an error, so wrap parse in try and catch when the text comes from outside.

keyvalue
JSON.stringifyobject → text
JSON.parsetext → object
Strictdouble quotes, no comments
Can't storefunctions, undefined

Summary

JSON is how data travels as text. Stringify turns objects into text, and parse turns text back into objects. Next, copying objects safely.

Key takeaways
  • JSON.stringify
  • JSON.parse
  • Strict format
Next up: Copying Objects — references and spread