JSON JSONP

Introduction to JSONP, JSON formatter, the server file, the JavaScript function, and creating a dynamic script tag

JSONP


JSONP: a method for sending JSON data without worrying about cross-domain issues.

JSONP doesn’t use the XMLHttpRequest object but the <script> tag instead.


JSONP Intro

JSONP (JSON with Padding).

Requesting a file from another domain can cause problems, due to cross-domain policy.

Requesting an external script from another domain doesn’t have this problem.

JSONP uses this advantage, and request files using the the script tag instead of the XMLHttpRequest object.

<script src=”demo_jsonp.php”>

The Server File

The file on the server wraps the result inside a function call:

Example

<?php
$myJSON = ‘{ “name”:”John”, “age”:30, “city”:”New York” }’;

echo “myFunc(“.$myJSON.”);”;
?>

The result returns a call to a function named “myFunc” with the JSON data as a parameter.

Make sure that the function exists on the client.

The JavaScript function

The function named “myFunc” is located on the client, and ready to handle JSON data:

Example

function myFunc(myObj) {
document.getElementById(“demo”).innerHTML = myObj.name;
}


Create a Dynamic Script Tag

The example above will execute the “myFunc” function when the page is loading, based on where you put the script tag, which is not very satisfying.

The script tag should only be created when needed:

Example

Create and insert the <script> tag when a button is clicked:

function clickButton() {
var s = document.createElement(“script”);
s.src = “demo_jsonp.php”;
document.body.appendChild(s);
}

Dynamic JSONP Result

The examples above are still very static.

Make the example dynamic by sending JSON to the php file, and let the php file return a JSON object based on the information it gets.

PHP file

<?php
header(“Content-Type: application/json; charset=UTF-8”);
$obj = json_decode($_GET[“x”], false);

$conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”);
$result = $conn->query(“SELECT name FROM “.$obj->$table.” LIMIT “.$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo “myFunc(“.json_encode($outp).”)”;
?>

PHP File explained:

  • Convert the request into an object, using the PHP function json_decode().
  • Access the database, and fill an array with the requested data.
  • Add the array to an object.
  • Convert the array into JSON using the json_encode() function.
  • Wrap “myFunc()” around the return object.

JavaScript Example

The “myFunc” function will be called from the php file:

function clickButton() {
var obj, s
obj = { “table”:”products”, “limit”:10 };
s = document.createElement(“script”);
s.src = “jsonp_demo_db.php?x=” + JSON.stringify(obj);
document.body.appendChild(s);
}
function myFunc(myObj) {
var x, txt = “”;
for (x in myObj) {
txt += myObj[x].name + “<br>”;
}
document.getElementById(“demo”).innerHTML = txt;
}

Access JSON object in Javascript

How to access JSON object in Javascript

JSON String:
{
    "name": "mkyong",
    "age": 30,
    "address": {
        "streetAddress": "88 8nd Street",
        "city": "New York"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "111 111-1111"
        },
        {
            "type": "fax",
            "number": "222 222-2222"
        }
    ]
}

To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via “.” or “[]”.

JavaScript:
<script>
       var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';

	var json = JSON.parse(data);

	alert(json["name"]); //mkyong
	alert(json.name); //mkyong

	alert(json.address.streetAddress); //88 8nd Street
	alert(json["address"].city); //New York

	alert(json.phoneNumber[0].number); //111 111-1111
	alert(json.phoneNumber[1].type); //fax

	alert(json.phoneNumber.number); //undefined
</script>

JSON Interview Questions & Answers

5) Why must one use JSON over XML?

  • It is faster and lighter than XML as on the wire data format
  • XML data is typeless while JSON objects are typed
  • JSON types: Number, Array, Boolean, String
  • JSON types: Number, Array, Boolean, String
  • Fetching values is as simple as reading from an object property in your JavaScript code.

6). Mention what is JSON-RPC and JSON Parser?

  • JSON RPC:It is a simple remote procedure call protocol same as XML-RPC although it uses the lightweight JSON format instead of XML
  • JSON Parser:JSON parser is used to parse the JSON data into objects to use its value. It can be parsed by javaScript, PHP and jQuery.

7). Mention what is the file extension of JSON?

File extension of JSON is .json

8). Mention which function is used to convert a JSON text into an object?

To convert JSON text into an object “eval” function is used.

 

JSON Interview Questions & Answers

  1. Mention what is JSON?

JSON is a simple data exchange format.  JSON means JavaScript Object Notation; it is language and platform independent.
2.  Explain what is JSON objects?

An object can be defined as an unordered set of name/value pairs.  An object in JSON starts with {left brace} and finish or ends with {right brace}.  Every name is followed by: (colon) and the name/value pairs are parted by, (comma).

3.  Explain how to transform JSON text to a JavaScript object?

One of the common use of JSON is to collect JSON data from a web server as a file or HTTP request, and convert the JSON data to a JavaScript, ant then it avails the data in a web page.

4. Mention what is the rule for JSON syntax rules? Give an example of JSON object?

JSON syntax is a set of the JavaScript object notation syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Curly brackets hold objects
  • Square bracket holds arrays

JSON with Ajax

AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of interrelated web development techniques, in order to create asynchronous web applications. According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page.

Many developers use JSON to pass AJAX updates between the client and the server. Websites updating live sports scores can be considered as an example of AJAX. If these scores have to be updated on the website, then they must be stored on the server so that the webpage can retrieve the score when it is required. This is where we can make use of JSON formatted data.

Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX is used so that javascript can retrieve these JSON files when necessary, parse them, and perform one of the following operations −

  • Store the parsed values in the variables for further processing before displaying them on the webpage.
  • It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website.

–    Example

The following code shows JSON with AJAX. Save it as ajax.htm file. Here the loading function loadJSON() is used asynchronously to upload JSON data.

<html>

<head>

<metacontent=”text/html; charset = ISO-8859-1″http-equiv=”content-type”>

function loadJSON(){

var data_file=”http://www.tutorialspoint.com/json/data.json&#8221;;

var http_request =newXMLHttpRequest();

try{

// Opera 8.0+, Firefox, Chrome, Safari

http_request =newXMLHttpRequest();

}catch(e){

// Internet Explorer Browsers{

try{

http_request =newActiveXObject(“Microsoft.XMLHTTP”);

}catch(e){

// Something went wrong

alert(“Your browser broke!”);

returnfalse;

}

}

}

http_request.onreadystatechange =function(){

if(http_request.readyState ==4){

// Javascript function JSON.parse to parse JSON data

var jsonObj = JSON.parse(http_request.responseText);

// jsonObj variable now contains the data structure and can

// be accessed as jsonObj.name and jsonObj.country.

document.getElementById(“Name”).innerHTML = jsonObj.name;

document.getElementById(“Country”).innerHTML = jsonObj.country;

}

}

http_request.open(“GET”, data_file,true);

http_request.send();

}

<title>tutorialspoint.com JSON</title>

</head>

 

<body>

<h1>Cricketer Details</h1>

<tableclass=”src”>

<tr><th>Name</th><th>Country</th></tr>

<tr><td>Sachin

</td>

<td>India

</td></tr>

</table>

Update Details

</body>

</html>

Given below is the input file data.json, having data in JSON format which will be uploaded asynchronously when we click the Update Detail button. This file is being kept in http://www.tutorialspoint.com/json/

{“name”: “Brett”, “country”: “Australia”}

The above HTML code will generate the following screen, where you can check AJAX in action –

Cricketer Details

Name Country
Sachin India

When you click on the Update Detail button, you should get a result something as follows. You can try JSON with AJAX yourself, provided your browser supports Javascript.

Cricketer Details

Name Country
Brett Australia

 

JSON in JAVA

JSON with Java

This chapter covers how to encode and decode JSON objects using Java programming language. Let’s start with preparing the environment to start our programming with Java for JSON

–  Environment

Before you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.

–  Mapping between JSON and Java entities

JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.

JSON Java
string java.lang.String
number java.lang.Number
true|false java.lang.Boolean
null null
array java.util.List
object java.util.Map

On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject.

–  Encoding JSON in Java

Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap.

import org.json.simple.JSONObject;

class JsonEncodeDemo {

       public static void main(String[] args){

      JSONObject obj = new JSONObject();



       obj.put("name", "foo");

      obj.put("num", new Integer(100));

      obj.put("balance", new Double(1000.21));      

      obj.put("is_vip", new Boolean(true));       



      System.out.print(obj);

   }

}

On compiling and executing the above program the following result will be generated –

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Following is another example that shows a JSON object streaming using Java JSONObject −

import org.json.simple.JSONObject;

class JsonEncodeDemo {

      public static void main(String[] args){

               JSONObject obj = new JSONObject();       

              obj.put("name","foo");

             obj.put("num",new Integer(100));      

             obj.put("balance",new Double(1000.21));      

             obj.put("is_vip",new Boolean(true)); 

    

           StringWriter out = new StringWriter();      

         obj.writeJSONString(out);

         String jsonText = out.toString();      

          System.out.print(jsonText); 

     }

}

On compiling and executing the above program the following result will be generated –

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

–  Decoding JSON in Java

The following example makes use of JSONObject and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List.

import org.json.simple.JSONObject;

import org.json.simple.JSONArray;

import org.json.simple.parser.ParseException;

import org.json.simple.parser.JSONParser; 



class JsonDecodeDemo {    

          

     public static void main(String[] args){               



            JSONParser parser = new JSONParser();

           String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";

          try{ 

                Object obj = parser.parse(s); 

                JSONArray array = (JSONArray)obj;                                   

    

               System.out.println("The 2nd element of array");         

               System.out.println(array.get(1));         

               System.out.println();



              JSONObject obj2 = (JSONObject)array.get(1);         

             System.out.println("Field \"1\"");         

             System.out.println(obj2.get("1")); 



              s = "{}"; 

             obj = parser.parse(s);         

             System.out.println(obj); 



           s = "[5,]";

            obj = parser.parse(s); 

           System.out.println(obj);

         

       s = "[5,,2]"; 

            obj = parser.parse(s); 

           System.out.println(obj); 

   }catch(ParseException pe){                          



            System.out.println("position: " + pe.getPosition());         

           System.out.println(pe);

       }

    }

}

On compiling and executing the above program, the following result will be generated −

The 2nd element of array

{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

 Field "1"

{"2":{"3":{"4":[5,{"6":7}]}}}

{}

[5]

[5,2]

 

 

Json with Ruby

  Json with Ruby

This chapter covers how to encode and decode JSON objects using Ruby programming language. Let’s start with preparing the environment to start our programming with Ruby for JSON.

–  Environment

Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your machine, otherwise let’s follow the following single step assuming you already have gem installed −

–  $gem install json

Parsing JSON using Ruby

The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let’s keep the following content in a file called input.json.

{ 

  "President": "Alan Isaac",  

"CEO": "David Richardson",   



  "India": [   

             "Sachin Tendulkar",  

            "Virender Sehwag",
             "Gautam Gambhir"  

],  



  "Srilanka": [ 

            "Lasith Malinga",  

            "Angelo Mathews",  

            "Kumar Sangakkara"  

 ], 

   "England": [     

            "Alastair Cook",  

             "Jonathan Trott",  

             "Kevin Pietersen"  

     ]       

}

Given below is a Ruby program that will be used to parse the above mentioned JSON document –

#!/usr/bin/ruby

require 'rubygems'

require 'json'

require 'pp' 



json = File.read('input.json')

obj = JSON.parse(json) 

pp obj

On executing, it will produce the following result –

{ 

        "President"=>"Alan Isaac",  

         "CEO"=>"David Richardson",

        "India"=> 

         ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"], 

        "Srilanka"=>  

       ["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],  

        "England"=> 

         ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]

}

 

Json with Python

JSON with Python:

This chapter covers how to encode and decode JSON objects using Python programming language. Let’s start with preparing the environment to start our programming with Python for JSON.

 Environment

Before you start with encoding and decoding JSON using Python, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed Demjson as follows –

$tar xvfz demjson-1.6.tar.gz

$cd demjson-1.6

$python setup.py install

–  JSON Functions

Function Libraries
encode Encodes the Python object into a JSON string representation.
decode Decodes a JSON-endoded string into a Python object.

–  Encoding JSON in Python (encode)

Python encode() function encodes the Python object into a JSON string representation.

Syntax

demjson.encode(self, obj, nest_level=0)

–  Example

The following example shows arrays under JSON with Python.

#!/usr/bin/python

import demjson

 data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] 

json = demjson.encode(data)

print json

While executing, this will produce the following result −

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

 Decoding JSON in Python (decode)

Python can use demjson.decode() function for decoding JSON. This function returns the value decoded from json to an appropriate Python type.

– Syntax

demjson.decode(self, txt)

Example

The following example shows how Python can be used to decode JSON objects

#!/usr/bin/python

import demjson

 json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

 text = demjson.decode(json)print  text

On executing, it will produce the following result −

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

 

Json with Perl

JSON with Perl:

This chapter covers how to encode and decode JSON objects using Perl programming language. Let’s start with preparing the environment to start our programming with Perl for JSON.

–   Environment

Before you start encoding and decoding JSON using Perl, you need to install JSON module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or any other latest version, follow the steps mentioned below –

$tar xvfz JSON-2.53.tar.gz

$cd JSON-2.53

$perl Makefile.PL

$make$make install

–   JSON Functions

Function Libraries
encode_json Converts the given Perl data structure to a UTF-8 encoded, binary string.
decode_json Decodes a JSON string.
to_json Converts the given Perl data structure to a json string.
from_json Expects a json string and tries to parse it, returning the resulting reference.
convert_blessed Use this function with true value so that Perl can use TO_JSON method on the object’s class to convert an object into JSON.

Encoding JSON in Perl (encode_json)

Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string.

–  Syntax

-      $json_text = encode_json ($perl_scalar );

-      

-       or

-      $json_text = JSON->new->utf8->encode($perl_scalar);

Example

The following example shows arrays under JSON with Perl −

-          #!/usr/bin/perl

-          use JSON;

-          my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

-          my $json = encode_json \%rec_hash;

-          print "$json\n";

While executing, this will produce the following result −

{"e":5,"c":3,"a":1,"b":2,"d":4}

The following example shows how Perl objects can be converted into JSON −

#!/usr/bin/perl 

package Emp;

sub new {  

        my $class = shift;  

          my $self = {   

           name => shift, 

          hobbies  => shift,

         birthdate  => shift,

   };           

   bless $self, $class;   

  return $self; 

} 

sub TO_JSON { return { %{ shift() } }; } 

package main;

use JSON;



 my $JSON = JSON->new->utf8;

$JSON->convert_blessed(1);



 $e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm");

$json = $JSON->encode($e);

print "$json\n";

On executing, it will produce the following result −

{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}

 Decoding JSON in Perl (decode_json)

Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.

–  Syntax

$perl_scalar = decode_json $json_text

 or 

$perl_scalar = JSON->new->utf8->decode($json_text)

–  Example

The following example shows how Perl can be used to decode JSON objects. Here you will need to install Data::Dumper module if you already do not have it on your machine.

#!/usr/bin/perl

use JSON;

use Data::Dumper; 

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 

$text = decode_json($json);

print  Dumper($text);

On executing, it will produce following result −

$VAR1 = { 

          'e' => 5, 

            'c' => 3,

            'a' => 1, 

           'b' => 2, 

          'd' => 4

};