Skip to main content

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;
       });
});

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object . How to create a namespace in JavaScript? Create one global object, and all variables, methods, and functions become properties of that object. Example:  // global namespace var MYAPP = MYAPP || {}; Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP How to create sub namespaces? // sub namespace MYAPP.event = {}; Class JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance. Example: var Person = function () {}; Explaination: Here we define a new class called Person with an empty constructor. Use the class keyword class Calculation {}; A class expr...

How to Add Next Previous links to The Event Calendar

Add Next/Previous links to The Event Calendar Wordpress Plugin Add code to your child theme’s functions.php file /**  * Allows visitors to page forward/backwards in any direction within month view */ if ( class_exists( 'Tribe__Events__Main' ) ) { class ContinualMonthViewPagination {     public function __construct() {         add_filter( 'tribe_events_the_next_month_link', array( $this, 'next_month' ) );         add_filter( 'tribe_events_the_previous_month_link', array( $this, 'previous_month' ) );     }     public function next_month() {         $url = tribe_get_next_month_link();         $text = tribe_get_next_month_text();         $date = Tribe__Events__Main::instance()->nextMonth( tribe_get_month_view_date() );         return '<a data-month="' . $date . '" href="' . $url . '" rel="next"...