In this article, I am going to talk about JSON and jQuery. We will learn how to define simple and complicated JSON and how to retrieve the JSON data using jQuery.
What is JSON?
JSON refers to JavaScript Object Notation. We use JSON to transfer the data from server to client and client to server.
How to define JSON
JSON is always defined as key-value pair.
Eg
- var jsonObject = {
- "Key": "value",
- "Key2": "value2"
- };
In the above example, I have defined a JSON object that is having a unique key and its corresponding value.
- var JsonObject = {
- "facebookId": "abc",
- "facebookPassword": "123"
- };
In the above example, we can see that "facebookId" and "facebookPassword" are the keys and "abc" and "123" are their corresponding values.
How to retrieve JSON data using jQuery.
We can find the JSON object value using its key. Let us see how to retrieve JSON values.
First, we use object name and then put dot(.) followed by the key name.
- var facebookIdvalue = jsonObject.facebookId;
- var facebookPasswordvalue = jsonObject.facebookPassword;
Now, it's time to work with complicated JSON objects.
Level1
- var data1={"facebookId":"abc","facebookPassword":"123"} ;
Retrieving the data from JSON Object.
- var facebookPasswordvalue = jsonObject.facebookPassword;
Level2
- var data2 = [{
- "Id": "abc",
- "Password": "123"
- }, {
- "Id": "xyz",
- "Password": "1258"
- }];
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 loop in jQuery.
- $.each(data2, function (index, value) {
- Console.log(value.Id);
- Console.log(value.Password);
- });
Level 3
- var userInfo= {
- "shipping_address": {
- "street_address": "1600 Pennsylvania Avenue NW",
- "city": "Washington",
- "state": "DC"
- }
- }
Retrieving the data
- (firstkey= userInfo).(secondkey= shipping_address).(value= city)
- var shippingAddCity= userInfo. shipping_address. city;
Output - “Washington”.
Level 4
- var comp = {
- "facebook": [{
- "userID": "989",
- "Password": "123"
- }, {
- "userID": "nothing",
- "Password": "NoPass"
- }, {
- "userID": "nothing",
- "Password": "NoPass"
- }, {
- "userID": "nothing",
- "Password": "NoPass"
- }]
- };
Retrieving the data
- var userdata= comp. facebook[0]. userID;
- Output userdata=”989”