JSON: the language of data

Lesson 2 of 12 12 min read Free lesson

Write JSON correctly, convert between JSON and JavaScript, and create JSON in PHP.

What JSON looks like

student.json
{
  "name": "Ada Okafor",
  "age": 17,
  "member": true,
  "parish": null,
  "courses": ["HTML", "CSS", "PHP"],
  "address": { "city": "Lagos", "country": "Nigeria" }
}
RuleExample
Keys always in double quotes"name"
Strings in double quotes (never single)"Ada"
Numbers, true, false, null without quotes17, true, null
Arrays in [ ]["HTML", "CSS"]
Objects in { }{ "city": "Lagos" }
No comments and no trailing commas...

JSON in JavaScript

JavaScript Try it in CodeLab
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]}
Output
Kemi
92
{"name":"Kemi","scores":[88,92,75]}

JSON in PHP

student.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.

Starting code Try it in CodeLab
const json = '';
Show a possible solution
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?

Quick check

Which turns JSON text into a JavaScript object?

Quick check

Which PHP function outputs JSON?

Hi there! đź‘‹ Have a question about the courses or joining the class? Ask me.