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

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...