avatarOmar Elgabry

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3520

Abstract

er you are going to use Object or Arrays, both contain values, and here is the list of all values that can be presented in <i>JSON</i> data:</p><ol><li>a string in double quotes</li><li>a number</li><li>boolean; true or false</li><li>null</li><li>an object</li><li>an array</li></ol><p id="c83b">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.</p><p id="83d5">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.</p><h1 id="1ed2">3. Putting All Together — Facebook API</h1><p id="b3fc">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.</p><p id="758c">In this example, I am going to demonstrate how to get, parse and iterate over the JSON data.</p><blockquote id="c24f"><p>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.</p></blockquote><h2 id="6817">1. JSON data</h2><p id="f2a1">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.</p><div id="4513"><pre>{ <span class="hljs-string">"data"</span>: [ { <span class="hljs-string">"id"</span>: <span class="hljs-string">"X12"</span>, <span class="hljs-string">"from"</span>: { <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Kennedy"</span>, <span class="hljs-string">"id"</span>: <span class="hljs-string">"1458633"</span> }, <span class="hljs-string">"message"</span>: <span class="hljs-string">"JSON is much easier and better than XML"</span>, <span class="hljs-string">"actions"</span>: [ { <span class="hljs-string">"name"</span>: <span class="hljs-string">"Comment"</span>, <span class="hljs-string">"link"</span>: <span class="hljs-string">"http://www.facebook.com/X999/posts/Y999"</span> }, { <span class="hljs-string">"name"</span>: <span class="hljs-string">"Like"</span>, <span class="hljs-string">"link"</span>: <span class="hljs-string">"http://www.facebook.com/X999/posts/Y999"</span> } ], <span class="hljs-string">"type"</span>: <span class="hljs-string">"status"</span>, <span class="hljs-string">"created_time"</span>: <span class="hljs-string">"2010-08-02T22:27:44+0000"</span>, <span class="hljs-string">"updated_time"</span>: <span class="hljs-string">"2010-08-02T22:27:44+0000"</span> }, { <span class="hljs-string">"id"</span>: <span class="hljs-string">"X45"</span>, <span class="hljs-string">"from"</span>: { <span class="hljs-string">"name"</span>: <span class="hljs-string">"Anna Smith"</span>, <span class="hljs-string">"id"</span>: <span class="hljs-string">"12587521"</span> }, <span class="hljs-string">"message"</span>: <span class="hljs-string">"On my way to write my very first JSON snippet"</span>, <span class="hljs-string">"actions"</span>: [ { <

Options

span class="hljs-string">"name"</span>: <span class="hljs-string">"Comment"</span>, <span class="hljs-string">"link"</span>: <span class="hljs-string">"http://www.facebook.com/X998/posts/Y998"</span> }, { <span class="hljs-string">"name"</span>: <span class="hljs-string">"Like"</span>, <span class="hljs-string">"link"</span>: <span class="hljs-string">"http://www.facebook.com/X998/posts/Y998"</span> } ], <span class="hljs-string">"type"</span>: <span class="hljs-string">"status"</span>, <span class="hljs-string">"created_time"</span>: <span class="hljs-string">"2010-08-02T25:27:44+0000"</span>, <span class="hljs-string">"updated_time"</span>: <span class="hljs-string">"2010-08-02T25:27:44+0000"</span> } ] }</pre></div><h2 id="be2b">2. Ajax Call</h2><p id="3c94">In order to get the JSON data, we need to send an Ajax request,</p><div id="5045"><pre>$.getJSON( <span class="hljs-string">"facebook.json"</span>, successFn);</pre></div><blockquote id="543b"><p><i>getJSON()</i>” method automatically parses the JSON data to JavaScript Object. If you want to parse the JSON data you can use the standard JavaScript function “<i>JSON.parse(data);</i>”, or the alternatively using <a href="http://jquery.com/"><i>jQuery</i></a><i>jQuery</i>.<i>parseJSON(data);</i></p></blockquote><h2 id="ca92">3. Loop through JSON data</h2><div id="6896"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">successFn</span>(jsonData,status, xhr){ // facebookPosts <span class="hljs-keyword">is</span> an <span class="hljs-keyword">array</span>, same as <span class="hljs-string">"data"</span> <span class="hljs-keyword">in</span> json file. var facebookPosts = jsonData.data; </pre></div><div id="6df7"><pre> for (var i<span class="hljs-operator">=</span><span class="hljs-number">0</span><span class="hljs-comment">; i < facebookPosts.length; i++){</span></pre></div><div id="5284"><pre> var id = facebookPosts[i].id; var <span class="hljs-keyword">from</span> = facebookPosts[i].<span class="hljs-keyword">from</span>.name; var msg = facebookPosts[i].message; var <span class="hljs-keyword">type</span> = facebookPosts[i].<span class="hljs-keyword">type</span>; var firstAction = facebookPosts[i].actions[<span class="hljs-number">0</span>].name;

          console.log(<span class="hljs-keyword">from</span>+ " of ID: "+id+" wrote: "+msg+" as a "+<span class="hljs-keyword">type</span>);
          //  John Kennedy <span class="hljs-keyword">of</span> ID: X12 wrote: <span class="hljs-type">JSON</span> <span class="hljs-keyword">is</span> much easier <span class="hljs-keyword">and</span> better than <span class="hljs-type">XML</span> <span class="hljs-keyword">as</span> a status
         // Anna Smith <span class="hljs-keyword">of</span> ID: X45 wrote: <span class="hljs-keyword">On</span> my way <span class="hljs-keyword">to</span> <span class="hljs-keyword">write</span> my very first <span class="hljs-type">JSON</span> snippet <span class="hljs-keyword">as</span> a status
       }
       

}</pre></div><p id="db92">You have reached the end of this tutorial! Download the whole code snippet, and share if you find it useful.</p><h2 id="8625">Download the code snippet, and share if you find it useful.</h2></article></body>

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:

  1. a string in double quotes
  2. a number
  3. boolean; true or false
  4. null
  5. an object
  6. 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 jQueryjQuery.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.

Download the code snippet, and share if you find it useful.

JavaScript
Json
Web Development
Recommended from ReadMedium