Friday, May 26, 2017

Differences between JSON and JSONP

What are the differences between JSON and JSONP? Are they the same? Let's find out.

JSON vs JSONP

JSON is a language designed for lightweight data exchange in an format that is easy for both humans and computers to understand. See: JSON formatter for more information.
JSON language could work on a technology which is not restricted by the same origin policy with only a small amount of changes required. The combination of this tech, along with the adapted form of JSON was branded JSONP.
The new technology that is fundamental to JSONP is nothing more than the bog-standard <script> tag. 
The full power of the <script> tag is often overlooked, or at the very least, taken for granted:
  1. <script> tags are not restricted by any same origin policy, so can make requests to any domain.
  2. <script> tags can be added programatically, which allows developers to request resources via the <script> tag as and when required:
    var element = document.createElement("script"); // create the element
    element.src = 'http://somewhere.com/some/resource.js'; // set the target resource
    document.getElementsByTagName("head")[0].appendChild(element); // add the element to the DOM
  3. The src attribute of the <script> tag is not restricted to just JavaScript files. Whatever the target, it will be retrieved via the relevant transport protocol (HTTP GET/ HTTPS GET), and the content will be evaluated by the JavaScript engine. If the content is not valid JavaScript, a Parse Error will be thrown.
JSONP is JSON with padding. 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});

1 comment:

  1. You have worked to perfection on this article. Thanks for taking the time to post search valuable information. I Recommendation this. Online JSON Formatter

    ReplyDelete