What is JSON? Follow
JSON stands for JavaScript Object Notation and is a text based way of representing simple and complex data. JSON is a subset of the JavaScript programming language and widely used to share data across the web in an interchangeable format. Due to its lightweight nature, JSON has taken over from XML as a way of representing hierarchical data structures. More information can be found on the official json.org website.
What is JSON used for?
While JSON is capable of being used to represent a single value such as a temperature reading, it is very good when more complex sets of data need to be represented as a single object. An example of this is where all of the information about a person or collection of people needs to be stored or shared. A single person's information might include such things as their full name, job title, telephone number and address. Each piece of information has both a key (describes what the information is, such as FirstName) and a valueassociated with that key (such as James). Each of these individual pieces of information are grouped into an object which fully describes the person.
Example of a Person JSON object
{
firstName: "James",
lastName: "Smith",
jobTitle: "Sales Manager",
telephone: "0800 123 4567",
emails: [
"my-email@work.com",
"my-email@home.com"
],
address: {
houseNumber: 216,
street: "Main Street",
city: "London",
country: "UK",
zip: "NW10 5EQ"
}
}
JSON syntax
JSON is built on two basic structures:
- A collection of key / value pairs (an object)
- An ordered list of values (an array)
These two structures can be combined in a hierarchical way to create more complex objects such as the Person example above. In this example, the Person object contains some simple key / value pairs (KVP) and the address which is an embedded child object made up of simple KVPs.
Object syntax
Defining an object
A JSON object is always contained within a matching set of curly braces {....}. All KVPs within these opening and closing curly braces are part of that single object. Where an object contains child objects, those child objects have their own set of matching curly braces (see address in example above).
Elements within an object, such as KVPs, are separated by a comma, with no comma after the last element.
It is common practice when writing JSON to indent each part of the hierarchy using either tabs or spaces and to put each KVP on a new line. These whitespace characters are not part of the JSON spec and are only added to make the JSON more human readable. It is equally valid to have a single line of text with no spaces, indents or newlines and most JSON has the whitespace removed before transmitting across the web to reduce the size of the transmission. Where an object only contains one or two simple KVPs it can be written on a single line.
{
temperature: 23.5,
setpoint: 18
}
{start: 12, end: 18}
Defining a key / value pair
Key / value pairs are used to represent a single element within a JSON object. They always comprise a key name (no white space is allowed within a key name) and a value, separated by a semicolon. (key: value)
The value of a key / value pair can be a simple data type such as a string or number, or it could be an entire child object or array.
When defining key names it is common practice to use camel case - writing compound words or phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation (firstName, jobTitle etc.)
firstName: "James"
lastName: "Smith"
age: 48
lightIsOn: true
Defining an array
JSON arrays are ordered lists of values. Unlike a KVP, array elements do not have a key but are referenced by their position within the list. Indexing of the positions always starts at zero so the first element is at index 0, the second at index 1, the third at index 2 etc. with the last element being at index array length -1.
The elements of an array are always contained within a matching set of square braces [....]and separated by a comma.
An array element may be any valid JSON value type, such as a number, string, or even a JSON object or JSON array, but all elements in an array should be of the same type (this is not mandatory but it is common practice).
Depending on the array length or element type, arrays can be defined on a single line or on multiple lines. Using multiple lines is only done to make the JSON more human readable.
[12,45,87.3,19.104]
[
{x: 10, y: 15},
{x: -12, y: 23},
{x: 0, y: -4}
]
JSON value types
JSON has seven valid value types. Any of these types may be used as the value of a key / value pair or the value of an element in an array. Use the object or array types to create complex nested objects.
The JSON types are as follows:
JSON Type | Description | Example(s) |
string | A sequence of zero or more Unicode characters wrapped in double quotes. Strings are used to represent words or sentences. | "This is a text string" |
number | An integer or floating point number. Thousands separators are not allowed and a period is used as a decimal point. | 12.3, -18.95 or 3e7 |
boolean | A boolean value equal to either true or false | true, false |
object | A JSON object containing key / value pairs, wrapped in matching curly braces (as described above) | {temperature: 23} |
array | A JSON array containing a list of elements where each element is a JSON value, wrapped in square braces (as described above) | [12, 45, 87] |
null | An empty value (one that does not have an current value). This is different to an empty string | null |
Creating, and reading and writing JSON values in JavaScript
Although JSON can be used by many programming languages the following explanations and examples are done using JavaScript.
Creating a JSON object using JavaScript
JSON syntax in JavaScript follows the descriptions above. To create a new instance of a JSON object representing a room temperature controller whose values can be read and modified in JavaScript use the following syntax:
// Create a JSON object.
// This creates an object called myController
let myController = {
setpoint: 23,
actualTemperature: 20,
location: {
building: "Building 1",
room: "Kitchen"
},
schedule: [
{
on: "06:30",
off: "09:00"
},
{
on: "16:00",
off: "21:45"
}
]
}
The object above has two simple values for the setpoint and actual temperature, a nested object for the location and an array of objects for the on / off heating time schedule.
Reading values from a JSON object using JavaScript
Once an object instance has been created you can read the values of the elements as follows:
// Create a JSON object.
// This creates an object called myController
let myController = {
setpoint: 23,
actualTemperature: 20,
location: {
building: "Building 1",
room: "Kitchen"
},
schedule: [
{
on: "06:30",
off: "09:00"
},
{
on: "16:00",
off: "21:45"
}
]
}
// Access the object values
// This prints the actual temperature of myController to the screen - in JavaScript the command console.log()
// prints the value inside the brackets to the screen
console.log(myController.actualTemperature)
// This prints the room where the controller is installed to the screen
console.log(myController.location.room)
// This prints the first and then second elements of the schedule to the screenconsole.log(myController.schedule[0])
console.log(myController.schedule[1])
The example above shows how, by using the hierarchical key names of the key / value pairs separated by dots, it is possible to get the value of the elements in the object.
To get the value of a specific element you always start with the name of the instance of the object followed by a dot, followed by the key name etc. If the object has nested objects you need to provide the keys for the full path, so to get the room value the full path is myController.location.roomand notjust myController.room.
Array elements are accessed by appending the desired index sandwiched by square braces to the array name. To get the first element in the schedule array (indexes start from 0) the full path is myController.schedule[0], and the second element's full path is myController.schedule[1]etc.
Writing a value to a JSON object using JavaScript
Once an object instance has been created you can modify the values of the elements as follows:
// Create a JSON object.
// This creates an object called myController
let myController = {
setpoint: 23,
actualTemperature: 20,
location: {
building: "Building 1",
room: "Kitchen"
},
schedule: [
{
on: "06:30",
off: "09:00"
},
{
on: "16:00",
off: "21:45"
}
]
}
// Modify the object values
// This updates the setpoint value
myController.setpoint = 21
// This updates the schedule time for the second 'on' time but leaves the off time as it was
myController.schedule[1].on = "17:10"
// This updates Bothe the 'on' and 'off' times of the second schedule
myController.schedule[1] = {on: "18:00", off: "22:30"}
// This reads the actual temperature and increments it by one
myController.actualTemperature = myController.actualTemperature + 1
The example above shows how, by using the hierarchical key names of the key / value pairs separated by dots, it is possible to modify the value of the elements in the object.
To modify the value of a specific element you always start with the name of the instance of the object followed by a dot, followed by the key name etc. If the object has nested objects you need to provide the keys for the full path, so to modify the room value the full path is myController.location.roomand notjust myController.room.
Array elements are accessed by appending the desired index sandwiched by square braces to the array name. To get the first element in the schedule array (indexes start from 0) the full path is myController.schedule[0], and the second element's full path is myController.schedule[1]etc.
Comments
0 comments
Please sign in to leave a comment.