/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Wednesday, July 1, 2015

JSON JavaScript Object Notation (JSON) Interview Question and Answer Part-1


JSON JavaScript Object Notation (JSON) is a format for storing and exchanging text information and is smaller than XML, faster and easier to parse and is language independent. JSON is syntax for storing and exchanging text information.

Parsing - Parsing is the process of analyzing a string of symbols, either in natural language or in computer languages. To parse is to divide words and phrases into different parts in order to understand relationships and meaning.

What is JSON? JSON stands for JavaScript Object Notation. JSON is a lightweight, language independent data interchange format.

How does JSON format looks like? The format of JSON is as shown in the below code. It starts with a simple curly brackets, followed with comma separated value and pair and finally ending with a curly bracket. 
The good part of JSON it just gets translated to JavaScript objects. For instance in the below figure you can see how the person variable has been transformed in to a person object with “FirstName” and “LastName” property.

History of JSON:
The name behind popularizing the JSON is  Douglas Crockford . He used JSON is his company State Software around 2001. In 2005, Yahoo started using JSON in its web services. In later 2006, Google started offering JSON in its GData Web Protocol. Today, JSON is one of the most widely used data-interchange format in web, and supported by most of the Web APIs (like Twitter API) to fetch public data and creating applications out of them.

Usage of JSON:
Various Web Services and APIs use JSON format to provide public data. Using the associated Service / API, you can fetch that data and use it to create applications.


Comparison with XML:

 Since both JSON and XML are mean to be a data interchange format, there is always a comparison between JSON (JavaScript Object Notation) and XML(Extensible Markup Language).

Similarities with XML:
·         Both (JSON and XML) are plain text.
·         Both are ‘self describing’ (human readable).
·         Both can be transported using AJAX.
·         Both can be parsed using JavaScript.
·         Both can be used with modern programming language.

Dissimilarities with XML:
·         JSON is much quicker to read and write in comparison to XML
·         In JSON text can be parsed using JavaScript inbuilt function eval().
·         JSON supports data structures(name/value pairs and ordered list of values
·         XML is redundant in nature unlike JSON.

Why JSON?
For AJAX applications, JSON is faster and easier than XML.

Using XML:
·         Fetch an XML document
·         Use the XML DOM to loop through the document
·         Extract values and store in variables

Using JSON:
·         Fetch a JSON string
·         eval() the JSON string

JSON Syntax Rule:
JSON syntax is a subset of the JavaScript object notation syntax.
·         Data is in name/value pairs
·         Data is separated by comma
·         Curly brackets holds objects
·         Square brackets holds arrays

JSON name/value pairs:
JSON data is written as ‘name/value’ pairs. A ‘name/value’ pair consists of a field name (in double quotes), followed by a colon (:), and followed by a value:

Syntax:

"firstName" : "Arun Kumar Singh"

Here ‘firstName’ is JSON variable name and ‘Arun Kumar Singh’ is JSON value.

JSON Values:
A JSON values can be:
·         A number(integer and floating point)
·         A String (in double quotes)
·         A Boolean (true or false)
·         An Array (in square brackets)
·         An objects(in curly braces)
Let’s see an example on how to create JSON object with JavaScript.
Example: In this example, simply I have created JSON object and store some values after then set these values into proper names.

                 JSON Object Creation Demo            

JSON Object Creation in JavaScript


Name:
Age:
Address:
Phone:



Output:
Save the above code in html format and execute in with web browser.





JSON is a lightweight way of data exchange between two entities. If you want your ASP.NET page to emit JSON data, you need to use namespace “System.Runtime.Serialization” namsepace. To convert your c# classes to light weight JSON format we need to use “DataContractJsonSerializer” class as shown in the below code snippet.

Person myPerson = new Person("Chris", "Pietschmann");
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End();



What is Full form of JSON?
JSON stands for JavaScript object notation.

What exactly does this JSON do?
It helps us to present and exchange data in a self-descriptive and independent way.

Was not SOAP meant to do the same thing?
SOAP is heavy due to XML tags. For example a SOAP message “Shiv” will become short , sweet and light in JSON like “Name” : “Shiv”

Do all technologies support JSON?
Yes , Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.

[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
string GetData();
If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.
public JsonResult  CustomerJson()
{
     List obj1 = new List();
Thread.Sleep(5000);
            Customer obj = new Customer();
obj.CustomerCode = "1001";
obj1.Add(obj);
returnJson(obj1,JsonRequestBehavior.AllowGet);
}

When not to use JSON?
We use JSON mostly when data exchange to our own server.
We should avoid using JSON when exchanging data from partner
sites. As JSON may contain some malicious script. XML would
be a better option here. 

EXPLAIN JSON STRUCTURES

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. These are universal data structures supported.

A JSON object is an unordered set of name/value pairs.

A JSON object begins with { (left brace) and ends with } (right brace).Each name is followed by : (colon) and the name/value pairs are separated by , (comma)

WHAT THE SECURITY AND JSON PARSER

Security and JSON Parser to understand by below examples 

// Include http://www.json.org/json.js
var myObject = myJSONtext.parseJSON();
eval() can compile and execute any JavaScript program, so there can be security issues (cross-site scripting)

Use eval() when the source can be trusted
When security is a concern - the source cannot be trusted -, it is better to use a JSON parser
A JSON parser will only recognize JSON text and so is much safer Object to Text Conversion
var myJSONText = myObject.toJSONString();
You can convert JSON object into JSON text
JSON does not support cyclic data structure
Do not give cyclical structures to the JSON stringifier

WHAT IS JSON FILE TYPE?
The file type for JSON files is ".json"

WHY USE JSON OVER XML?
Lighter and faster than XML as on-the-wire data format
JSON objects are typed while XML data is typeless
JSON types: string, number, array, boolean,
XML data are all string
Native data form for JavaScript code
Data is readily accessible as JSON objects in your JavaScript
code vs. XML data needed to be parsed and assigned to variables through tedious DOM APIs
Retrieving values is as easy as reading from an object property in your JavaScript code

WHAT IS MIME TYPE OF JSON
The MIME type JSON text is "application/json"

EXPLAIN JSON ARRAY?
JSON array written as following  An array can contain multiple objects:  
JSON Array
{
"student":[
{"firstName":"Samuel","lastName":"Fernandes"},
{"firstName":"Takeshi","lastName":"Okada"},
{"firstName":"Jacob","lastName":"Rasel"}]
}

WHAT IS JSON PARSER?
The eval() function can compile and execute any JavaScript. This represents a potential security problem. It is safer to use a JSON parser used to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.

HOW TO CONVERT JSON TEXT TO A JAVASCRIPT OBJECT?
One of the most common uses of JSON is to fetch JSON data from a web server (as a file or as an HttpRequest), convert the JSON data to a JavaScript object, and then it uses the data in a web page.



SOAP is heavy due to XML tags. For example a SOAP message "Shiv" will become short , sweet and light in JSON like "Name" : "Shiv". Second most important it evaluates as javascript object. To convert the complicated SOAP XML in to javascript JSON object would be a tough and tedious task.


Figure: - SOAP meant to do the same thing

Yes, Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.

[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
string GetData();
If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.
public JsonResult  CustomerJson()
{
     List obj1 = new List();
     Thread.Sleep(5000);
            Customer obj = new Customer();
            obj.CustomerCode = "1001";
            obj1.Add(obj);
            return Json(obj1,JsonRequestBehavior.AllowGet);
}

If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code.”myPerson” is the class.

DataContractJsonSerializer serializer = new DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End();

Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF , ASP.NET , MVC etc as discussed in the previous questions.

public JsonResult  getEmployee()
{
Emp obj = new Emp();
obj.empcode = "1001";
return Json(obj,JsonRequestBehavior.AllowGet);
}

To make a call to the above MVC action using Jquery we need to use “getJSON” method. Below is the simple code for the same. It has three parameters: -

  • The first parameter is the URL which emits out JSON. For instance in the below code the URL is “/Employee/getEmployee”.
  • The next parameter helps us to pass data to the resource which emits out JSON currently it’s the MVC action. Currently we are only doing a get so the second parameter is NULL for now.
  • The last parameter is the call back function which will be invoked once the MVC action returns data. You can see how the “getData” function just displays the “empcode” property. Because the output is in JSON it automatically converts the JSON data to javascript object.
$.getJSON("/Employee/getEmployee", null, getData);
function getData(data)
{
alert(data.empcode);
}

We can use the “post” method of jquery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the call back function where we receive the response.

var mydata ={name:"Shiv",city:"Mumbai"};
$.post("/Send/Request", // URL
mydata , // Data to be sent
function(data,status){alert(data + “ “ + status);}); // Call back function

To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of Jquery.”DisplayData” is a callback function to handle the output given by the server.

var Mydata = $("#form1").serialize();
$.post("/Customer/getCustomer", MyData, DisplayData);

How to Generate or Send JSON Data at the Server Side?
Create JSONObject Java object
Add name and value pairs using put method
 Convert it to String type using toString method and send it to the client with content-type as "text/xml" or "text/plain"
myString = new JSONObject().put("JSON", "Hello, World!").toString();
// myString is {"JSON": "Hello, World"}

How to Receive JSON Data at the Client Side?
Create JSON JavaScript object
Use "POST" HTTP method in the open method of the XMLHttpRequest object
Pass JSON JavaScript object in the send method of XMLHttpRequest object
var carAsJSON = JSON.stringify(car);
var url = "JSONExample?timeStamp=" + new Date().getTime(); createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON);

How to Receive JSON Data at the Server Side?

 Read the JSON data as a String type
Create JSONObject Java object from the string String json = readJSONStringFromRequestBody(request);
//Use the JSON-Java binding library to create a JSON object in Java JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
}
catch(ParseException pe) {
}

No comments:

Post a Comment

My Blog List