\n\n\n```\n\n```js\n// File loaded from https://example.com?callback=printData\nprintData({ name: 'Yang Shun' });\n```\n\nThe client has to have the `printData` function in its global scope and the function will be executed by the client when the response from the cross-origin domain is received.\n\nJSONP can be unsafe and has some security implications. As JSONP is really JavaScript, it can do everything else JavaScript can do, so you need to trust the provider of the JSONP data.\n\nThese days, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) is the recommended approach and JSONP is seen as a hack."}},{"@type":"Question","name":"What is JSON and why would I use it?","acceptedAnswer":{"@type":"Answer","text":"**JSON** (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). Some JavaScript is not JSON, and some JSON is not JavaScript."}},{"@type":"Question","name":"Explain the structure of JSON","acceptedAnswer":{"@type":"Answer","text":"JSON is built on two structures:\n\n* 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.\n* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence."}},{"@type":"Question","name":"Are Javascript objects and JSON equivalent?","acceptedAnswer":{"@type":"Answer","text":"People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.\n\nIn Javascript `var x = {x:y}` is **not JSON**, this is a **Javascript object**. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be `var x = '{\"x\":\"y\"}'`. `x` is an object of type **string** not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, `var x = JSON.parse('{\"x\":\"y\"}');`, `x` is now an object but this is not JSON anymore.\n\nRemember: **JSON (in Javascript) is a string!**"}},{"@type":"Question","name":"What is the correct JSON content type?","acceptedAnswer":{"@type":"Answer","text":"The MIME media type for JSON text is **application/json**. The default encoding is UTF-8. (Source: RFC 4627)."}},{"@type":"Question","name":"Can I use comments inside a JSON file? If so, how?","acceptedAnswer":{"@type":"Answer","text":"No.\n\nThe JSON should all be data, and if you include a comment, then it will be data too.\n\nYou could have a designated data element called \"_comment\" (or something) that would be ignored by apps that use the JSON data.\n\n```js\n{\n \"_comment\": \"comment text goes here...\",\n \"glossary\": {\n \"title\": \"example glossary\",\n \"GlossDiv\": {\n \"title\": \"S\",\n \"GlossList\": {\n \"GlossEntry\": {\n \"ID\": \"SGML\",\n \"SortAs\": \"SGML\",\n \"GlossTerm\": \"Standard Generalized Markup Language\",\n \"Acronym\": \"SGML\",\n \"Abbrev\": \"ISO 8879:1986\",\n \"GlossDef\": {\n \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n \"GlossSeeAlso\": [\"GML\", \"XML\"]\n },\n \"GlossSee\": \"markup\"\n }\n }\n }\n }\n}\n```"}},{"@type":"Question","name":"What is JSONP, and why was it created?","acceptedAnswer":{"@type":"Answer","text":"**JSONP** stands for JSON with Padding.\n\nJSONP is a great away to get around cross-domain scripting errors. You can consume a JSONP service purely with JS without having to implement a AJAX proxy on the server side.\n\nJSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.\n\nThese days, CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice."}},{"@type":"Question","name":"How should I parse a JSON string in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"The standard way to parse JSON in JavaScript is `JSON.parse()`\n\nThe JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:\n\n```js\nconst json = '{ \"fruit\": \"pineapple\", \"fingers\": 10 }';\nconst obj = JSON.parse(json);\nconsole.log(obj.fruit, obj.fingers);\n```"}},{"@type":"Question","name":"How could I parse a JSON string in older browser?","acceptedAnswer":{"@type":"Answer","text":"The standard way to parse JSON in JavaScript is `JSON.parse()`. The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse(). \n\nIf you can't use external libs first of all, you have to make sure that the JSON code is valid. After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.\n\nOn the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the `eval` function.\n\nThis is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the `eval` function allows for renegade code if you will.\n\nHere is an example of using the eval function:\n\n```js\nvar strJSON = '{\"result\":true,\"count\":1}';\nvar objJSON = eval(\"(function(){return \" + strJSON + \";})()\");\nalert(objJSON.result);\nalert(objJSON.count);\n```\n"}},{"@type":"Question","name":"Which data format is the right one for JSON?","acceptedAnswer":{"@type":"Answer","text":"JSON itself _does not specify_ how dates should be represented, but JavaScript does.\n\nYou should use the format emitted by `Date.prototype.toJSON()` method:\n```js\n//2012-04-23T18:25:43.511Z\n```\n\nHere's why:\n\n* It's human readable but also succinct\n* It sorts correctly\n* It includes fractional seconds, which can help re-establish chronology\n* It conforms to ISO 8601\n* ISO 8601 has been well-established internationally for more than a decade\n* ISO 8601 is endorsed by W3C, RFC3339, and XKCD"}},{"@type":"Question","name":"What is the difference between YAML and JSON?","acceptedAnswer":{"@type":"Answer","text":"**YAML** is a human-readable data serialization standard that can be used in conjunction with all programming languages and is often used to write configuration files.\n\nTechnically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON, but not necessarily the other way around. Right now, AJAX and other web technologies tend to use JSON. YAML is currently being used more for offline data processes. JSON is the winner for performance (if relevant) and interoperability. YAML is better for human-maintained files.\n\nAlso consider:\n\n* YAML, depending on how you use it, can be more readable than JSON\n* JSON is often faster and is probably still interoperable with more systems\n* It's possible to write a \"good enough\" JSON parser very quickly\n* Duplicate keys, which are potentially valid JSON, are definitely invalid YAML.\n* YAML has a ton of features, including comments and relational anchors. YAML syntax is accordingly quite complex, and can be hard to understand.\n* It is possible to write recursive structures in yaml: {a: &b [*b]}, which will loop infinitely in some converters. Even with circular detection, a \"yaml bomb\" is still possible (see xml bomb).\n* Because there are no references, it is impossible to serialize complex structures with object references in JSON. YAML serialization can therefore be more efficient.\n* In some coding environments, the use of YAML can allow an attacker to execute arbitrary code."}},{"@type":"Question","name":"Explain the difference between JSON.stringify() and JSON.parse()","acceptedAnswer":{"@type":"Answer","text":"`JSON.stringify` turns a JavaScript object into JSON text and stores that JSON text in a string, eg:\n\n```js\nvar my_object = {\n key_1: \"some text\",\n key_2: true,\n key_3: 5\n};\n\nvar object_as_string = JSON.stringify(my_object);\n// \"{\"key_1\":\"some text\",\"key_2\":true,\"key_3\":5}\" \n\ntypeof(object_as_string);\n// \"string\" \n```\n\n`JSON.parse` turns a string of JSON text into a JavaScript object, eg:\n\n```js\nvar object_as_string_as_object = JSON.parse(object_as_string);\n// {key_1: \"some text\", key_2: true, key_3: 5} \n\ntypeof(object_as_string_as_object);\n// \"object\" \n```"}},{"@type":"Question","name":"What are the differences between JSON and JSONP?","acceptedAnswer":{"@type":"Answer","text":"**JSONP** is **JSON with padding**, that is, you put a string at the beginning and a pair of parenthesis around it. For example:\n\n```js\n//JSON\n{\n \"name\": \"stackoverflow\",\n \"id\": 5\n}\n//JSONP\nfunc({\n \"name\": \"stackoverflow\",\n \"id\": 5\n});\n```\n\nThe result is that you can load the JSON as a script file. If you previously set up a function called `func`, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that **example.com** is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the **example.com** domain:\n\n```js\nfunction func(json) {\n alert(json.name);\n}\nvar elm = document.createElement(\"script\");\nelm.setAttribute(\"type\", \"text/javascript\");\nelm.src = \"http://example.com/jsonp\";\ndocument.body.appendChild(elm);\n```"}},{"@type":"Question","name":"Is there a standard on JSON naming? ","acceptedAnswer":{"@type":"Answer","text":"There is no single standard, but I have seen three styles:\n\n* **\"Pascal/Microsoft, Java\"**\", like `camelCase`\n* **\"C\"** with underscores, like `snake_case`\n* **\"kebab-case\"** like `longer-name`"}},{"@type":"Question","name":"Why must one use JSON over XML?","acceptedAnswer":{"@type":"Answer","text":"* It is faster and lighter than XML as on the wire data format\n* XML data is typeless while JSON objects are typed\n* JSON types: Number, Array, Boolean, String\n* XML data are all string\n* Data is readily available as JSON object is in your JavaScript\n* Fetching values is as simple as reading from an object property in your JavaScript code"}},{"@type":"Question","name":"What are the limitations and uses of JSON?","acceptedAnswer":{"@type":"Answer","text":"There are some:\n\n* JSON is not suitable for handling very large and complex data. When the data gets complex with several nested and hierarchical structures, it becomes complex for human readability. \n* JSON does not support the comments. \n* It does not support to handle the multimedia formats like image or rich text format."}}]}
FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

16 JSON Interview Questions You Must Be Prepared For

There really is no substitute for JSON. Well supported, great tooling and native support for JSON in Javascript, numerous server-side languages and even new solutions for API’s like GraphQL still rely on JSON for data. Follow along and check the list of 16 common JSON interview questions and answers you must be prepared for.

Q1: 
What is JSON and why would I use it?

Answer

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). Some JavaScript is not JSON, and some JSON is not JavaScript.


Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q2: 
How should I parse a JSON string in JavaScript?

Answer

The standard way to parse JSON in JavaScript is JSON.parse()

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q3: 
What is the correct JSON content type?

Answer

The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627).


Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q4: 
Are Javascript objects and JSON equivalent?

Answer

People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.

In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.

Remember: JSON (in Javascript) is a string!


Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q5: 
Can I use comments inside a JSON file? If so, how?

Answer

No.

The JSON should all be data, and if you include a comment, then it will be data too.

You could have a designated data element called "_comment" (or something) that would be ignored by apps that use the JSON data.

{
   "_comment": "comment text goes here...",
   "glossary": {
      "title": "example glossary",
      "GlossDiv": {
         "title": "S",
         "GlossList": {
            "GlossEntry": {
               "ID": "SGML",
               "SortAs": "SGML",
               "GlossTerm": "Standard Generalized Markup Language",
               "Acronym": "SGML",
               "Abbrev": "ISO 8879:1986",
               "GlossDef": {
                  "para": "A meta-markup language, used to create markup languages such as DocBook.",
                  "GlossSeeAlso": ["GML", "XML"]
               },
               "GlossSee": "markup"
            }
         }
      }
   }
}

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q6: 
Explain the difference between JSON.stringify() and JSON.parse()

Answer

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:

var my_object = {
    key_1: "some text",
    key_2: true,
    key_3: 5
};

var object_as_string = JSON.stringify(my_object);
// "{"key_1":"some text","key_2":true,"key_3":5}"  

typeof(object_as_string);
// "string" 

JSON.parse turns a string of JSON text into a JavaScript object, eg:

var object_as_string_as_object = JSON.parse(object_as_string);
// {key_1: "some text", key_2: true, key_3: 5} 

typeof(object_as_string_as_object);
// "object" 

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q7: 
Explain the structure of JSON

Answer

JSON is built on two 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.

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q8: 
What are the differences between JSON and JSONP?

Answer

JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it. For example:

//JSON
{
    "name": "stackoverflow",
    "id": 5
}
//JSONP
func({
    "name": "stackoverflow",
    "id": 5
});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json) {
     alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
What are the limitations and uses of JSON?

Answer

There are some:

  • JSON is not suitable for handling very large and complex data. When the data gets complex with several nested and hierarchical structures, it becomes complex for human readability.
  • JSON does not support the comments.
  • It does not support to handle the multimedia formats like image or rich text format.

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions
Source: educba.com

Q10: 
Why must one use JSON over XML?

Answer
  • 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
  • XML data are all string
  • Data is readily available as JSON object is in your JavaScript
  • Fetching values is as simple as reading from an object property in your JavaScript code

Having Tech or Coding Interview? Check 👉 15 JSON Interview Questions

Q11: 
Explain how JSONP works (and how it's not really Ajax)

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q12: 
Is there a standard on JSON naming?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q13: 
What is JSONP, and why was it created?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q14: 
What is the difference between YAML and JSON?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q15: 
Which data format is the right one for JSON?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
How could I parse a JSON string in older browser?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...