API Documentation 1: JSON and XML
JSON
JavaScript Object Notation
Introduction
This Lecture Covers
What is JSON?
Basic types
Arrays
Objects
Nesting
Indentation
JSON
JavaScript Object Notation
JavaScript is a programming language
JSON was originally created to hold structured
data to be used in JavaScript
JSON became so popular…
It is used for data for all kinds of applications
It is the most popular way of sending data for Web
APIs
Basic Data Types
Strings
Enclosed in single or double quotation marks
Numbers
Integer or decimal, positive or negative
Booleans
true or false
No quotation marks
null
Means “nothing”.
No quotation marks
Arrays
Arrays are lists
In square brackets [ ]
Comma-separated
Can mix data types
Examples:
[4, 6, 23.1, -4, 0, 56]
["red", "green", "blue"]
[65, "toast", true, 21, null, 100]
Objects
Objects are JSON’s dictionaries
They are enclosed in curly brackets { }
Keys and values are separated by a colon :
Pairs are separated by commas.
Keys and values can be any data type.
Example:
{"red":205, "green":123, "blue":53}
Nesting
Nesting involves putting arrays and objects
inside each other:
You can put arrays inside objects, objects
inside arrays, arrays inside arrays, etc.
Often a JSON file is one big object with lots of
objects and arrays inside.
Example JSON: Describing a song
{
"song":
{
"title": "Hey Jude",
"artist": "The Beatles",
"musicians":
["John Lennon", "Paul McCartney",
"George Harrison", "Ringo Starr"]
}
}
Example JSON: Describing a menu
{
"menu": [ File View
{ "header": "File",
"items": [ Open Zoom In
{"id": "Open", "label": "Open"},
{"id": "New", "label": "New"},
New Zoom Out
{"id": "Close", "label": "Close"}
Close Original View
] },
{ "header": "View",
"items": [
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "OriginalView", "label": "Original View"}
]}
]}
White Space and Indentation
“White space” means spaces, new lines, etc.
White space doesn’t matter
Unless it’s inside quotation marks
Good JSON formatting
In general, add an indent for every new level of
brackets
End lines with commas
Lots of exceptions to this!
Review
JSON represents structured data
Basic types: string, number, Boolean, null
Arrays (lists) use square brackets [ ]
Objects (dictionaries) use curly brackets { }
Collections can contain collections
White space doesn’t matter
Indent for every level of collection