JSON stands for JavaScript Object Notation. JSON is based off the JavaScript language and was originally created to hold structured data to be used in JavaScript. Because of it's simplicity, it became popular and used in all sorts of applications including the most popular way to send data for web APIs.
JSON has four basic types:
- Number
- Integer or decimal, positive or negative
- String
- Enclosed with single or double quotation marks
- Boolean
- True/false but used without any quotation marks
- null
- Means "nothing"; no quotation marks
What is a JSON Object
Objects are JSON's dictionaries and are enclosed using curly brackets({}). Objects are defined with a key/value pair. This pair is separated by a colon (:). Finally, pairs are separated by commas. Be sure to include commas and your closing brackets where necessary to ensure proper formatting. Otherwise, your JSON file will be rejected by the server it is being sent to.
Example of an JSON object:
{"make": "Saturn", "year": 2004, "color": "blue"}
Nesting
Nesting can involve arrays and objects sitting inside each other. You can put arrays inside objects, objects inside arrays, arrays inside arrays, and so on. Sometimes, a JSON file is one big object with huge collection of objects and arrays found within it.
Indentation
"White space" refers to spaces, new lines, and so on. Spacing doesn't matter in a JSON file unless it is inside a quotation mark. With that being said, it's good to be consistent in how you use white space to ensure that content in the file is human readable.
Properly formatted JSON includes
- An indent for every new level of brackets
- Commas on the end of every line unless it's the last line in the object
- There are always exceptions to this depending on how the JSON file is used.
Use JSON formatting tools like http://jslint.com/ and freeformatter.com to verify your formatting, find any missing commas, and improperly closed objects, lists, and so on.
JSON Object in Action
JSON objects start off with an opening curly bracket ({) and close with another (}) with the body of the object contained therein.
{
...
}
This object has only one key/value pair. In this example, the key is robot and the value is another object.
{
"robot":
{
...
}
}
Inside this robot object, there are three key/value pairs: type, weight, sensors
{
"robot":
{
"type": "roller",
"weight": 20,
"sensors":
["optical", "distance", "vibration", "fuel"]
}
}
In this case, the type value is a string, weight is a number, and sensors is an array.
In summary, the JSON example contains two objects (the robot object nested inside the main object), one array called sensors, four key/value pairs (robot object itself and it's value object, type, weight, and sensors pairs).