Retrieving JSON Data Using jQuery

Posted By : Pranav Kakkar | 01-Nov-2017

What is JSON?

JSON refers to Java-script Object-Notation. It uses JSON to transfer data from the server to the client and vice versa.

How we define JSON

JSON is always defined as the key-value pair.

Eg

var jsonObject = {  
    "Key": "value",  
    "Key1": "value1"  
};

In this example, I have defined a JSON object which is having a unique-key and it's corresponding value. 

var JsonObject = {  
    "facebookId": "pqr",  
    "facebookPassword": "456"  
};

In this example, we can see that the "facebookId" and the "facebook password" are the key and "pqr" and "456" are the corresponding values.

How to retrieve the JSON data using jQuery.
We can find that the JSON-object value's using its key. Now we'll see how to retrieve the JSON value.

Firstly, we use the object's name and then we put "dot(.)" following the key's name.

var facebookIdvalue = jsonObject.facebookId;  
var facebookPasswordvalue = jsonObject.facebookPassword; 

Now, it is time to work with the complicated JSON objects.

Level-1

var data1={"facebookId":"pqr","facebookPassword":"456"};

Retrieving the data from JSON Object. 

var facebookPasswordvalue = jsonObject.facebookPassword; 


Level-2 

var data2 = [{  
    "Id": "pqr",  
    "Password": "456"  
}, {  
    "Id": "mno",  
    "Password": "7569"  
}];

Retrieving a single value

var firstId = data2[0].id;  
var secondid = data2[1].id;  
var firstPassword = data2[0].Password;  
var secondPassword = data2[1].Password;

Retrieving all the values using Each of the loops in jQuery.

$.each(data2, function (index, value) {  
                    Console.log(value.Id);  
                    Console.log(value.Password);  
                });

Level-3

var userInfo= {  
                  "shipping_address": {  
                      "street_address": "8 Yemen road",  
                      "city": "Yemen",  
                      "state": "Yemen"  
                  }  
              }

Retrieving data 

(firstkey= userInfo).(secondkey= shipping_address).(value= city)  
var shippingAddCity= userInfo. shipping_address. city;  
Output  - “Yemen”.

Level-4 

var comp = {  
    "facebook": [{  
        "userID": "bcd",  
        "Password": "486"  
    }, {  
        "userID": "example",  
        "Password": "NoExample"  
    }, {  
        "userID": "example2",  
        "Password": "NoExample2"  
    }, {  
        "userID": "example3",  
        "Password": "NoExample3"  
    }]  
}; 

Retrieving the data 

var userdata= comp. facebook[0]. userID;  
Output userdata=”486”

 

About Author

Author Image
Pranav Kakkar

Pranav is a sharp intellectual UI Developer, he has a good Knowledge of HTML, CSS. His hobbies are Playing Cricket, Football, listening Music.

Request for Proposal

Name is required

Comment is required

Sending message..