JSON In a Nutshell
Storing and exchanging data especially between a server and web application is a major practice for most developers and even beginners. XML has been on the scene for several years, But there is an alternative solution called “JSON”.
Getting Started
Make sure that you are comfortable with JavaScript basic syntax.
In the final code snippet, I’ll be using Ajax with jQuery. So, make sure you are on a local server or on your web server.
1. What’s JSON?!
JSON stands for “JavaScript Object Notation”, It’s used to store and exchange data as an alternative solution for XML. JSON is easier to parse, quicker to read and write. JSON syntax is based on JavaScript Object Literals, But it’s a text format.
JSON is language-independent; means you can use parse and generate JSON data in other programming languages.
2. JSON Syntax
JSON syntax format is based on two main structures; Objects and Arrays. An Object is a collection of name/value pairs, and Array is an ordered list of values.
As I mentioned, JSON syntax is based on JavaScript Object Literals. So, You will see that Objects and Arrays here have the same syntax in JavaScript.
Object Declaration
{
"id": 4911,
"firstName":"John",
"lastName":"Walter",
"isStudent": true
};
You will notice that we declared JSON data based on an Object. This Object maybe represent a person's data. It has the id, firstName, lastName, and a boolean to check if the person is a student, or not.
Here is a couple of syntax format rules for Objects in JSON:
- An Object is a collection of name/value pairs
- It starts with the left curly brackets ‘{‘ and ends with right curly brackets ‘}’
- Each name in the Object is a string in a double quotation, and it’s followed by a colon ‘:’ then the value associated with that name.
- name/value pairs are separated by comma ‘,’
Array Declaration
[
"Belgium", "Brazil", "Cameroon", "Canada", "Chile", "Denmark"
]
The snippet above demonstrates how JSON can take the format of an Array. This array represents a list of string values.
Here is a couple of syntax format rules for Arrays in JSON:
- Arrays are ordered lists of values of the zero-based index.
- It starts with the left bracket ‘[‘ and ends with right brackets ‘]’
- Values are separated by comma ‘,’
Ok, now you should understand that JSON data will be declared based on either an Object or an Array.
But, the question is “What are the values that we can use in JSON?” whether with the values inside an Object or an Array.
3. JSON Values
Whether you are going to use Object or Arrays, both contain values, and here is the list of all values that can be presented in JSON data:
- a string in double quotes
- a number
- boolean; true or false
- null
- an object
- an array
We have already used strings, numbers, and boolean in our Object and Array declaration, But we can also have an array that has values of objects, null, and even other nested arrays.
Most commonly you will see JSON data is declared using an Object, that has name/value pairs. Again, values can be arrays, other objects, or any type listed above.
3. Putting All Together — Facebook API
If you decided one day to retrieve some data from Facebook, like the posts of your Facebook page, or search for all posts that have a specific keyword, chances are you will be receiving JSON data that will be parsed to a JavaScript Object.
In this example, I am going to demonstrate how to get, parse and iterate over the JSON data.
This is not the actual data that will be sent from facebook API, It’s nearly the same, and much more simple for demonstration purposes.
1. JSON data
For simplicity, I will be using a file with type ‘.json’(The file type for JSON files), It contains the JSON data. But, you can make an Ajax call for example to a URL expecting JSON data.
{
"data": [
{
"id": "X12",
"from": {
"name": "John Kennedy", "id": "1458633"
},
"message": "JSON is much easier and better than XML",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T22:27:44+0000",
"updated_time": "2010-08-02T22:27:44+0000"
},
{
"id": "X45",
"from": {
"name": "Anna Smith", "id": "12587521"
},
"message": "On my way to write my very first JSON snippet",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T25:27:44+0000",
"updated_time": "2010-08-02T25:27:44+0000"
}
]
}
2. Ajax Call
In order to get the JSON data, we need to send an Ajax request,
$.getJSON( "facebook.json", successFn);
“getJSON()” method automatically parses the JSON data to JavaScript Object. If you want to parse the JSON data you can use the standard JavaScript function “JSON.parse(data);”, or the alternatively using jQuery “jQuery.parseJSON(data);”
3. Loop through JSON data
function successFn(jsonData,status, xhr){
// facebookPosts is an array, same as "data" in json file.
var facebookPosts = jsonData.data; for (var i=0; i < facebookPosts.length; i++){ var id = facebookPosts[i].id;
var from = facebookPosts[i].from.name;
var msg = facebookPosts[i].message;
var type = facebookPosts[i].type;
var firstAction = facebookPosts[i].actions[0].name;
console.log(from+ " of ID: "+id+" wrote: "+msg+" as a "+type);
// John Kennedy of ID: X12 wrote: JSON is much easier and better than XML as a status
// Anna Smith of ID: X45 wrote: On my way to write my very first JSON snippet as a status
}
}
You have reached the end of this tutorial! Download the whole code snippet, and share if you find it useful.