Obtain the JSON

Use an API named XMLHttpRequest (XHR) to obtain the JSON. This is a very useful JavaScript object to make network requests to retrieve resources from a server via JavaScript. You can update small content. There’s no need to reload the entire page. More responsive web pages now!

Obtain the JSON

  • Store the URL of the JSON you want to retrieve in a variable. Add the following at the bottom of your JavaScript code:
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  • Create a new request object instance from the XMLHttpRequest constructor, using the new keyword. Add the following below your last line:
var request = new XMLHttpRequest();
  • Open a new request using the open() method. Add this:
request.open('GET', requestURL);

This takes at least two parameters. Other option is to use the two mandatory ones for this simple example:

– The HTTP method to use when making the network request. GET is fine.
– The URL to make the request to.  This is the URL of the JSON file that is stored earlier.

  • Set the responseType to JSON, so that XHR knows that the server will be returning JSON and that this should be converted behind the scenes into a JavaScript object. Add the following two lines. Then send the request with the send() method:
request.responseType = 'json';
  • Wait for the response to return from the server and deal with it. Add the following code below your previous code:
request.onload = function() {
  var superHeroes = request.response;

Here you are storing the response to our request (available in the response property) in a variable called superHeroes. This variable will now contain the JavaScript object based on the JSON.




JSON PHP – Guide and examples

This article will show you how to exchange JSON data between the client and a PHP server.

The PHP File

PHP has some built-in functions to handle JSON.

Use the PHP function json_encode() to convert objects in PHP into JSON or use JSON Formatter Online.

PHP file

$myObj->name = “John”;
$myObj->age = 30;
$myObj->city = “New York”;

$myJSON = json_encode($myObj);

echo $myJSON;

The Client JavaScript

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:


Use JSON.parse() to convert the result into a JavaScript object:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myObj.name;
xmlhttp.open(“GET”, “demo_file.php”, true);

PHP Array

Use the PHP function json_encode() to convert PHP into JSON

PHP file

$myArr = array(“John”, “Mary”, “Peter”, “Sally”);

$myJSON = json_encode($myArr);

echo $myJSON;

The Client JavaScript

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above:


Use JSON.parse() to convert the result into a JavaScript array:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myObj[2];
xmlhttp.open(“GET”, “demo_file_array.php”, true);

PHP Database

Make a request to the server where you ask for the first 10 records in the “customers” table:


Use JSON.stringify() to convert the JavaScript object into JSON:

obj = { “table”:”customers”, “limit”:10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML = this.responseText;
xmlhttp.open(“GET”, “json_demo_db.php?x=” + dbParam, true);

JSON Arrays and Examples

JSON arrays and examples. Learn about arrays as JSON objects, access JSON arrays, modify or delete JSON items or values, etc.

Arrays as JSON Objects

For example

[ “Ford”, “BMW”, “Fiat” ]

Arrays in JSON are nearly the same as in JavaScript.

Array values in JSON:  string, number, object, array, boolean or null.

Array values in Javascript: all of the above and other valid JavaScript expression, functions, dates, and undefined.

Arrays in JSON Objects

Arrays can be values of an object property:

For example:

“cars”:[ “Ford”, “BMW”, “Fiat” ]

Access Array Values

Use the index number.

See JSON formatter to learn more.

Loop Through an Array

Use a for-in loop to access array values

For Example:

for (i in myObj.cars) {
x += myObj.cars[i];

Or use a for loop:

For example:

for (i = 0; i < myObj.cars.length; i++) {
x += myObj.cars[i];

 Nested Arrays in JSON Objects

Values in an array can also be another array, or even another JSON object:

For example:

myObj = {
“cars”: [
{ “name”:”Ford”, “models”:[ “Fiesta”, “Focus”, “Mustang” ] },
{ “name”:”BMW”, “models”:[ “320”, “X3”, “X5” ] },
{ “name”:”Fiat”, “models”:[ “500”, “Panda” ] }

To access arrays inside arrays, use a for-in loop for each array:

For example:

for (i in myObj.cars) {
x += “<h1>” + myObj.cars[i].name + “</h1>”;
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];

Modify Array Values

Use the index number to modify an array:

Delete Array Items

Use the delete keyword to delete items from an array


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


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 (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:


$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:


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:


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

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

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

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);
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 “[]”.

       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

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.



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


// Opera 8.0+, Firefox, Chrome, Safari

http_request =newXMLHttpRequest();


// Internet Explorer Browsers{


http_request =newActiveXObject(“Microsoft.XMLHTTP”);


// Something went wrong

alert(“Your browser broke!”);





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



<title>tutorialspoint.com JSON</title>




<h1>Cricketer Details</h1>








Update Details



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 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.

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




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("num",new Integer(100));      

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

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


           StringWriter out = new StringWriter();      


         String jsonText = out.toString();      




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}]}}}}]";


                Object obj = parser.parse(s); 

                JSONArray array = (JSONArray)obj;                                   


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



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

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


              s = "{}"; 

             obj = parser.parse(s);         


           s = "[5,]";

            obj = parser.parse(s); 



       s = "[5,,2]"; 

            obj = parser.parse(s); 


   }catch(ParseException pe){                          

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





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

The 2nd element of array


 Field "1"







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 –


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",


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


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


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