What is JSON?
JavaScript Object Notation (JSON) is a language-independent text format for storing and exchanging data. Web applications use JSON to exchange data between a web browser and a server and exchange data between servers via REST API. For many programming languages, including JavaScript, Java, C ++, C #, Go, PHP, and Python, there are ready-made code libraries for creating and manipulating JSON data. JSON file names use the .json file extension.
What is Fetch API?
The Fetch API presents a new global fetch() method, which allows network requests to be made similarly to the XMLHttpRequest (XHR) method but more powerfully and flexibly. Fetch API is a better alternative to XMLHttpRequest and can be easily integrated with other technologies, such as Service Workers. The main difference between the Fetch API and XMLHttpRequest is that Fetch uses promises, which allows you to have a more straightforward and cleaner API without nested callbacks.
JavaScript Fetch JSON Example
Below are example of getting JSON from the ReqBin echo URL using Fetch API.
The response.text() method does not automatically parse the response body and resolves to a string. To automatically parse a JSON response into a JavaScript object, you need to use the response.json() method.
How to fetch JSON data in JavaScript?
To get JSON data from an API endpoint, you must first call the fetch() method and then response.json(). The fetch() method returns a Promise representing the server's response, and the response.json() resolves to the result of parsing the JSON response into a JavaScript object.
How to POST JSON data using Fetch API?
To post JSON data to the server using the Fetch API, you need to tell fetch() to use the POST method and pass the JSON data in the "body" parameter. The Content-Type: 'application/json' HTTP header is necessary for the server to correctly receive and interpret the JSON data in the body of the HTTP message.
How to fetch JSON data using HTTP POST method?
To fetch JSON data from the server using the HTTP POST method, you need to tell fetch() to make a POST request by passing the "method: 'POST'".
How to fetch JSON using JavaScript async and await operators?
To fetch JSON data using JavaScript's async and await operators, you must first call await fetch() to resolve it to a Response object and then call await response.json() to resolve it to a parsed JSON object.