Sunday, 4 December 2016

JSON and JSONP in Javascripit

JSON and JSONP in Javascripit
JSON is a subset of the object literal notation of JavaScript.
JSON in JavaScript
Example:
var myJSONObject = {"Address": [
{"city": "Azamgarh", "state": "Uttar Pradesh", "country": "INDIA"},
{"city": "Lucknow", "state": "Delhi", "country": "USA"},
{"city": "Noida", "state": "Goa", "country": "UK"}
]
};
Code Explaination:
  1. Here bindings is an object.
  2. It contains array of 3 object.
  3. Members can be retrieved using dot or subscript operators.

Example: myJSONObject.bindings[0].method
JSON Objects
JSON objects are written inside curly braces
Example: var name = {"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
Example: var employeeList = "employees":[
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter", "lastName":"Jones"}
]
JSON.stringify() turns a Javascript object into JSON text and stores that JSON text in a string.
Syntax:JSON.stringify(value[, replacer[, space]])
Example: JSON.stringify({ x: 5 }); Output: '{"x":5}'

Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
function replacer(key, value) {
// Filtering out properties
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'

The JSON.parse() turns a string of JSON text into a Javascript object
Example: var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
console.log(obj.count) return 1;

Or use can use like this
obj = JSON && JSON.parse(json) || $.parseJSON(json);

JSON in PHP
Basicall in PHP JSON has 3 main functions
json_encode: Returns the JSON representation of a value.
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
json_decode: Decodes a JSON string.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
json_decode($json, true);
?>
json_last_error: Returns the last error occurred.
   
Cross-browser handling of Ajax requests
JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data. It does this by having the server return JSON data wrapped in a function call (the “padding”) which can then be interpreted by the browser.JSONP is used to request data from a server residing in a different domain.

function logResults(json){
console.log(json);
}

$.ajax({
url: "https://api.github.com/users/jeresig",
dataType: "jsonp",
jsonpCallback: "logResults"
});

It can be written as
$.getJSON("https://api.github.com/users/jeresig?callback=?",function(json){
console.log(json);
});
JSON jQuery Syntax
$.getJSON(url, data, success);
Example:
$.getJSON('example.json', function (data) {
console.log(data);
});

This script contains the callback function.
<script src="http://www.example.com?q=w3r_callback"><script>

Create CallBack function

function w3r_callback(data){
console.log(data);
}

JSONP is mostly used to get data using RESTFull APIs(like Flicker).

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
       tags: "dogs",
       tagmode: "any",
       format: "json"
},
function(data) {
     $.each(data.items, function(i,item){
             $("<img/>").attr("src", item.media.m).appendTo("#images");
             if ( i == 3 ) return false;
       });
});

0 comments:

Post a Comment