CPIT-405 · WEB APPLICATIONS
JSON
Part 4: The language of web data
What is JSONSyntax rulesData typesJSON vs XMLJSON.stringifyJSON.parseValidation
01 · WHAT IS JSON?
JavaScript Object Notation
browser
{"name": "Ali"}{"ok": true}
server
works with
JavaScriptPythonJavaPHPGoC#
02 · SYNTAX RULES
Everything is a key and a value
{ "name": "Ali", "age": 20 }
"keys"always strings in double quotes
,commas between pairs
{ }an object
[ ]an array
user.json Content-Type: application/json
03 · DATA TYPES
26number
"Ali"string
trueboolean
[ … ]array
{ … }object
nullnull
{ "name": "Ali", "age": 26, "employed": true, "car": null, "address": { "city": "Jeddah", "street": "300 Airport Rd." }, "languages": ["JavaScript", "Python", "go"]}
stringnumberbooleannested objectarray
04 · JSON vs XML
JSON
{ "course": { "name": "Web Applications", "code": "CPIT", "number": 405 }}
XML
<!-- a comment in XML --><course> <name>Web Applications</name> <code>CPIT</code> <number>405</number></course>
✓ shorter
✓ faster
✓ easier to read
✓ JSON.parse() built in
✓ GitHub, Instagram APIs
✗ no comments in JSON
05 · DATA TRAVELS AS TEXT
Over HTTP, data is always a string
object{ name: "Ali" }
JSON.stringify() →
string'{"name":"Ali"}'
string'{"name":"Ali"}'
JSON.parse() →
object{ name: "Ali" }
06 · JSON.stringify(value)
let user = { name: "Ali", languages: ["JavaScript", "Python", "Go"]};let jsonText = JSON.stringify(user);
jsonText (a string)
"name":"Ali","languages":["JavaScript","Python","Go"]
ready to send→
server
07 · JSON.parse(text)
let jsonText = '{"name": "Ali", "languages": ["JavaScript", "Python", "Go"]}';let user = JSON.parse(jsonText);user.name // "Ali"
username: "Ali"languages: [3 items]

Ali

Programming Languages: JavaScript, Python, Go

user.languages.join(", ")
08 · VALIDATION
JSON.parse("{'name': 'Ali'}")
SyntaxError: Unexpected token '
✗{'name': 'Ali'}single quotes
✗{"a": 1, "b": 2,}trailing comma
✗{name: "Ali"}key without quotes
✓{"name": "Ali"}valid
VS Code: Format DocumentJSONLintbeautifiers format · linters find errors
NEXT
Your turn
Open the practice platform and start the Part 4 tab
Fix the JSONPredict the outputstringify & parse challenges
0:00 / 0:00
← All partsPractice Part 4 →
Space: play / pause · ← →: scenes · M: voice on / off · C: subtitles · F: fullscreenDeveloped by: Fatmah Bamashmoos