Difference between JSON and XML

What is JSON? What is XML? And what is the difference between JSON and XML? This article will give you the answer.

What is JSON?

JSON (JavaScript Object Notation), is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. Squarespace uses JSON to store and organize site content created with the CMS.

What is XML?

In computing, XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

What is the difference between JSON and XML?

Both JSON and XML can be used to receive data from a web server.


The following JSON and XML examples both defines an employees object, with an array of 3 employees:

JSON Example

{“employees”:[
{ “firstName”:”John”, “lastName”:”Doe” },
{ “firstName”:”Anna”, “lastName”:”Smith” },
{ “firstName”:”Peter”, “lastName”:”Jones” }
]}

XML Example

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

 JSON is Like XML Because

  • Both JSON and XML are “self describing” (human readable)
  • Both JSON and XML are hierarchical (values within values)
  • Both JSON and XML can be parsed and used by lots of programming languages
  • Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because

  • JSON doesn’t use end tag
  • JSON is shorter
  • JSON is quicker to read and write
  • JSON can use arrays

The biggest difference is:  XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

JSON vs XML

You can learn how to fix various issues regarding your mobile and gadgets by following https://geeksnation.net/ guides.

JSON Objects

Object Syntax

Example

{ “name”:”John”, “age”:30, “car”:null }

JSON objects are surrounded by curly braces {}.

JSON objects are written in key/value pairs.

Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.


Accessing Object Values

You can access the object values by using dot (.) notation:

Example

myObj = { “name”:”John”, “age”:30, “car”:null };
x = myObj.name;

You can also access the object values by using bracket ([]) notation:

Example

myObj = { “name”:”John”, “age”:30, “car”:null };
x = myObj[“name”];

Looping an Object

You can loop through object properties by using the for-in loop:

Example

myObj = { “name”:”John”, “age”:30, “car”:null };
for (x in myObj) {
document.getElementById(“demo”).innerHTML += x;
}

In a for-in loop, use the bracket notation to access the property values:

Example

myObj = { “name”:”John”, “age”:30, “car”:null };
for (x in myObj) {
document.getElementById(“demo”).innerHTML += myObj[x];
}

Nested JSON Objects

Values in a JSON object can be another JSON object.

Example

myObj = {
“name”:”John”,
“age”:30,
“cars”: {
“car1″:”Ford”,
“car2″:”BMW”,
“car3″:”Fiat”
}
}

You can access nested JSON objects by using the dot notation or bracket notation:

Example

x = myObj.cars.car2;
//or:
x = myObj.cars[“car2”];

Modify Values

You can use the dot notation to modify any value in a JSON object:

Example

myObj.cars.car2 = “Mercedes”;

You can also use the bracket notation to modify a value in a JSON object:

Example

myObj.cars[“car2”] = “Mercedes”;

Delete Object Properties

Use the delete keyword to delete properties from a JSON object:

Example

delete myObj.cars.car2;
JSON formatter tool is a web-based tool to view, edit, format, and validate JSON data: JSON formater and validator online

JSON HTML

JSON can very easily be translated into JavaScript. JavaScript can be used to make  HTML in your web pages.


HTML Table

Make an HTML table with data received as JSON:

Example

obj = { “table”:”customers”, “limit”:20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += “<table border=’1′>”
for (x in myObj) {
txt += “<tr><td>” + myObj[x].name + “</td></tr>”;
}
txt += “</table>”
document.getElementById(“demo”).innerHTML = txt;
}
}
xmlhttp.open(“POST”, “json_demo_db_post.php”, true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xmlhttp.send(“x=” + dbParam);

Dynamic HTML Table

Make the HTML table based on the value of a drop down menu: 
Choose an option:
Customers
Products
Suppliers

 Example
<select id=”myselect” onchange=”change_myselect(this.value)”>
<option value=””>Choose an option:</option>
<option value=”customers”>Customers</option>
<option value=”products”>Products</option>
<option value=”suppliers”>Suppliers</option>
</select>

function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = “”;
obj = { “table”:sel, “limit”:20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += “


for (x in myObj) {
txt += “

“;
}
txt += “

” + myObj[x].name + “


document.getElementById(“demo”).innerHTML = txt;
}
};
xmlhttp.open(“POST”, “json_demo_db_post.php”, true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xmlhttp.send(“x=” + dbParam);
}


HTML Drop Down List

Make an HTML drop down list with data received as JSON:

Example

obj = { “table”:”customers”, “limit”:20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += “<select>”
for (x in myObj) {
txt += “<option>” + myObj[x].name;
}
txt += “</select>”
document.getElementById(“demo”).innerHTML = txt;
}
}
xmlhttp.open(“POST”, “json_demo_db_post.php”, true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xmlhttp.send(“x=” + dbParam);
Free online tool to view, edit, validate, and format JSON: JSON formatter tool

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';
request.send();
  • 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;
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}

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

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

Example: 

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);
xmlhttp.send();

PHP Array

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

PHP file

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

Example:

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);
xmlhttp.send();

PHP Database

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

Example:

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);
xmlhttp.send();

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:

{
“name”:”John”,
“age”:30,
“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 = {
“name”:”John”,
“age”:30,
“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

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

  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