JSON: the language of data
Write JSON correctly, convert between JSON and JavaScript, and create JSON in PHP.
What JSON looks like
{
"name": "Ada Okafor",
"age": 17,
"member": true,
"parish": null,
"courses": ["HTML", "CSS", "PHP"],
"address": { "city": "Lagos", "country": "Nigeria" }
}
| Rule | Example |
|---|---|
| Keys always in double quotes | "name" |
| Strings in double quotes (never single) | "Ada" |
| Numbers, true, false, null without quotes | 17, true, null |
| Arrays in [ ] | ["HTML", "CSS"] |
| Objects in { } | { "city": "Lagos" } |
| No comments and no trailing commas | ... |
JSON in JavaScript
const text = '{"name":"Kemi","scores":[88,92]}';
const student = JSON.parse(text); // text -> object
console.log(student.name); // Kemi
console.log(student.scores[1]); // 92
student.scores.push(75);
const back = JSON.stringify(student); // object -> text
console.log(back); // {"name":"Kemi","scores":[88,92,75]}
Kemi
92
{"name":"Kemi","scores":[88,92,75]}JSON in PHP
<?php
header('Content-Type: application/json');
$student = ['name' => 'Tunde', 'courses' => ['HTML', 'CSS'], 'active' => true];
echo json_encode($student);
// {"name":"Tunde","courses":["HTML","CSS"],"active":true}
Exercise
Write JSON for a course with a title, a price of 7500, a free value of false, and a list of three lesson titles. Then parse it and log the second lesson.
const json = '';
Show a possible solution
const json = '{"title":"PHP and MySQL","price":7500,"free":false,"lessons":["Hello, PHP","Variables","Loops"]}';
const course = JSON.parse(json);
console.log(course.lessons[1]); // Variables
Check your understanding
Quick check
Which is valid JSON?
Why: Keys and strings need double quotes.
Quick check
Which turns JSON text into a JavaScript object?
Why: parse = text to object.
Quick check
Which PHP function outputs JSON?
Why: json_encode().