\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."}}]}
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.
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.
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);The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627).
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!
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"
}
}
}
}
}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" JSON is built on two structures:
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);There are some:
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...