JSON Interview Questions


Question 1:

What is JSON?

JSON stands for JavaScript Object Notation which is a lightweight data exchange format. Main reasons of its popularity are it's language independent, self descriptive, easy to understand and it's human-readable form. Code for parsing and generating JSON data is available in many programming languages such as Java, C#, Perl, Python etc. 

For example:-

{
     "firstName": "Amit",
     "lastName": "Gupta",
     "address": {
         "streetAddress": "P-265",
         "city": "Gurgaon",
         "state": "Haryana",
         "postalCode": 122015
     },
     "phoneNumberList": [
         "9999999999",
         "8888888888"
     ]
 }

 Hence JSON comprises of two parts i.e key and value also known as key/value pair.

  • Key: A key is string enclosed in quotation marks.
  • Value: A value can be a string, number, boolean expression, array, or object.

Types of Values

  • Array
  • Boolean
  • Number
  • Object
  • String

For example:-

In above JSON data,

firstName is a key whereas "Amit" is value i.e of String type.

postalCode is key whereas 122015 is value of Number type.

phoneNumberList is key whereas ["9999999999", "8888888888"].

address is key whereas the data within it is object type.

Question 2:

What are the advantages of JSON over XML?

  JSON XML
   JSON stands for "Java Script and Object Notation".  XML stands for "Extensible Markup Language".
Syntax and Verbosity JSON is much simpler than XML. JSON has a much smaller grammar and maps more directly onto the data structures.  XML contains start tag and end tags. Moreover it takes more number of characters to show data as compared to JSON.
Speed  JSON is light weighted. Hence it is faster than XML.  Due to tags and additional data, XML becomes heavy. Hence it is not as fast as JSON.
Document Sharing  Json typically is used to exchange traditional data formats like string, array and integers.  XML allows you to include data types like images, charts, and graphs which makes it more rich if you have to share and exchange such data.
Orientation  Json is data oriented, hence it can be easily mapped.  XML is document oriented, hence it requires more effort to map.
Usage   Used where speed is concern. For example: Mobile Application.  Used with SOAP web services to exchange data, used for configuration data.
Question 3:

How to convert JSON text into object in Javascript?

You can convert JSON text into object in JavaScript using following methods

Using JQuery

var jsonData = {
                 "name" : "Amit",
                 "company" : "Modern Pathshala"      
               }
var jsonObject = $.parseJSON(jsonString);

Using Javascript

var jsonData = {
                 "name" : "Amit",
                 "company" : "Modern Pathshala"      
               }
var jsonObject =JSON.parse(jsonString);
Question 4:

What is the use of JSON.stringify() method? 

JSON.stringify is used to convert a Javascript object into JSON text and stores that JSON text in a string.

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).
  • All symbol-keyed properties will be completely ignored, even when using the replacer function.
  • Non-enumerable properties will be ignored.

Following example illustrates how to use stringify() method to convert Javascript object to JSON string

JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))  // '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]); // '[1,"false",false]'

// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') }); // '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' }); // '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); // '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
  if (typeof k === 'symbol') {
    return 'a symbol';
  }
}); // '{}'

// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); // '{"y":"y"}'

Reference: stringify method docs

Question 5:

How can we post a complete HTML form in JSON format?

Often we have to send complete form data using Ajax to server. If the form data comprises of one or two parameter it can be achieved by manually forming the JSON data as shown below:

var data = {
              "name": $("#name").val(),
              "company" : $("#company").val()
           };
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

But assume if you have huge amount of form data that you have to send then it is advised to use serialize the form using serializeArray() method as shown below

var data = JSON.stringify($("#myForm").serializeArray());
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

Question 6:

What is MIME type for JSON?

The MIME media type for JSON text is application/json.

Question 7:

What is JSONP? What is the difference between JSON and JSONP?

We know that JSON is used to transport data. Using $.ajax() or $.getJSON() method you can get the JSON data as response. But what if you have to fetch the data from other domain using AJAX request. For example:- I have domain example.com and I want to fetch JSON data from example1.com using AJAX. This simple approach to fetch JSON data fails if the page is making the ajax calls to different domain. The Same Origin Policy of browser prohibits these type of cross-domain calls in some browser due to security threats.

To overcome this problem JSONP(JSON with Padding) is used. JSONP wraps up a JSON response into a JavaScript function and sends as a Script to the browser/client. The Same Origin Policy is not applied on Script and once the function is loaded it acts like JSON object that it contains.

When a $.getJSON(URL, function) is executed with a URL containing &callback=? JQuery will transparently create the script tag and the handler function. The script tag uses the URL as its src attribute and the handler is created using the function passed as the second argument.

When a $.getJSON(URL, function) is executed with a URL containing &callback=? JQuery will transparently create the script tag and the handler function. The script tag uses the URL as its src attribute and the handler is created using the function passed as the second argument.

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
});
Question 8:

Which technologies support JSON?

Major of the technologies like Java, Python, C# provide support of JSON.

Question 9:

Explain JSON Structure.

JSON comprises of two parts i.e key and value also known as key/value pair.

  • Key: A key is string enclosed in quotation marks.
  • Value: A value can be a string, number, boolean expression, array, or object.

Value Representation

Types of Values

  • Array
  • Boolean
  • Number
  • Object
  • String

For example:-

{
     "firstName": "Amit",
     "lastName": "Gupta",
     "address": {
         "streetAddress": "P-265",
         "city": "Gurgaon",
         "state": "Haryana",
         "postalCode": 122015
     },
     "phoneNumberList": [
         "9999999999",
         "8888888888"
     ]
 }

In above JSON data,

firstName is a key whereas "Amit" is value i.e of String type.

postalCode is key whereas 122015 is value of Number type.

phoneNumberList is key whereas ["9999999999", "8888888888"].

address is key whereas the data within it is object type.

Question 10:

How to send JSON data with request in Ajax?

You can use $.ajax() jQuery method to send JSON data as shown below

var data = {
             "name":"Amit", 
             "company":"Modern Pathshala"
} $.ajax({ dataType: "json", url: url, data: data, success: success });
Share interview questions

Comments

Comments
comments powered by Disqus

Navigation

Social Media