JSON

A notation for storing data

Web Typography Workshop @ Letterform Archive
Week 4

A JSON Object

JavaScript Object Notation is a way to store data for your website that uses a similar syntax to JavaScript Objects. JSON is a useful way to send and receive data, both within your website, as well as from external data sources through APIs (Application Programming Interface). More on JSON on MDN.

JSON Syntax

Basic JSON is a string like the following, with the quotations around the brackets. It can be setup from within the JavaScript file and assigned to a variable.


/* .js */
var color = {
    "name" : "mycolor", 
    "r": 255,
    "g": 0,
    "b": 0
};

JSON can be easily bulky and complex to load a length of data. In this case, JSON can be loaded into your project as a stand alone file. There are no variables in this file — it is just an object that starts with the curly brackets.

				
/* .json */
 {
    "name" : "mycolor",
    "r": 255,
    "g": 0,
    "b": 0
}

JSON Syntax

All property names have to be surrounded by double quotes, and only simple data expressions are allowed. No function calls, bindings, or anything that involves actual computation. Comments are not allowed in JSON either.

JSON can have more than one object, and also lets you create nested arrays.


/* .js */
var shapes = {
  "myshape": [
      { "shape": "circle", // this is data object [0]
        "r": 0,
        "g": 255,
        "b": 0 
      },
      { "shape": "square", // this is data object [1]
        "r": 255,
        "g": 0,
        "b": 0 
      }
   ]
};

Accessing JSON Data

You can retrieve the data from a json object in the same way as you might a normal JavaScript object, using the dot or [] notation. JSON can also contain arrays, which are accessed similarly as well.


/* .js */
var color = {
    "name" : "mycolor", 
    "r": 255,
    "g": 0,
    "b": 0
};

var shapes = {
  "myshape": [
      { "shape": "circle", // this is data object [0]
        "r": 0,
        "g": 255,
        "b": 0 
      },
      { "shape": "square", // this is data object [1]
        "r": 255,
        "g": 0,
        "b": 0 
      }
   ]
};

color.name //mycolor
color.r //255
shapes.myshape[0].r //0
shapes.myshape[1].shape //square

Formatting JSON Data

JSON syntax is strict — a missing " or , will trip up the script from reading the data properly. If you are used to spreadsheets for data, you might use a converter like CSVtoJSON to output your formatted JSON.