DEV Community

Anurag Affection
Anurag Affection

Posted on

JSON vs JSONP

Difference between JSON & JSONP

JSON is a data format commonly used for data interchange between a client and a server, while JSONP is a technique used to fetch JSON data from a different domain in web applications by dynamically injecting script tags into the DOM and using callback functions to handle the response.

JSON (JavaScript Object Notation):

  • JSON is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
  • It is language-independent, but it is primarily used with JavaScript due to its close relationship with JavaScript objects.
  • JSON is a text-based format and is typically used for transmitting data between a server and a web application.
  • JSON data is structured as key-value pairs and supports arrays and nested objects.
  • JSON is parsed using the JSON.parse()method in JavaScript and is generated using the JSON.stringify() method.
{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com",
  "address": {
    "city": "New York",
    "country": "USA"
  },
  "hobbies": ["reading", "gardening", "traveling"]
}

Enter fullscreen mode Exit fullscreen mode

JSONP (JSON with Padding):

  • JSONP is a technique used to overcome the Same-Origin Policy limitations in web browsers when making cross-domain requests.
  • It is essentially a way of fetching JSON data from a different domain in a web page that is hosted on a different domain.
  • JSONP works by inserting a <script> tag into the DOM with a src attribute pointing to a URL that returns JSON data. This URL includes a callback function as a query parameter.
  • The server returns JSON data wrapped in a function call, where the function name is the callback specified in the URL. This allows the JSON data to be executed as JavaScript code in the context of the web page.
  • JSONP is primarily used for making cross-domain AJAX requests in web applications when the server supports JSONP callbacks.
  • Suppose we have a server that provides JSON data about users. Let's say the URL to fetch user data is https://example.com/users?callback=myCallback.
  • When you make a request to this URL with a specified callback function, the server responds with JSON data wrapped in a function call matching the specified callback function. Here's how the response might look:
myCallback({
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com",
  "address": {
    "city": "New York",
    "country": "USA"
  },
  "hobbies": ["reading", "gardening", "traveling"]
});

Enter fullscreen mode Exit fullscreen mode
  • When this response is executed in the browser, it will invoke the myCallback function with the JSON data as an argument. This allows you to use the JSON data in your JavaScript code, overcoming the Same-Origin Policy restrictions for cross-domain requests.

Top comments (0)