Parsing JSON using fetch API
In this approach, fetching JSON data from web APIs, the fetch API returns responses in JSON format. Utilizing the JSON JSON () method of fetch, developers can seamlessly parse these responses into JavaScript objects.
Run the below command:
npm install node-fetch
node index.js
Updated Dependencies:
{
"type": "module",
"dependencies": {
"node-fetch": "^3.3.2"
}
}
Example: The code below shows How to Parse JSON in JavaScript using fetch API.
import fetch from 'node-fetch';
// The Random User Generator API provides a new set
// of randomly generated user data with each request
fetch('https://api.randomuser.me/')
// Handling the response asynchronously
.then(response => response.json())
// Processing the parsed JSON data
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Output:
{
results: [
{
gender: 'male',
name: [Object],
location: [Object],
email: 'ajinkya.rao@example.com',
login: [Object],
dob: [Object],
registered: [Object],
phone: '8621840038',
cell: '9145280882',
id: [Object],
picture: [Object],
nat: 'IN'
}
],
info: { seed: '209009bdf461ec82', results: 1, page: 1, version: '1.4' }
}
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipulation and retrieval in your JavaScript projects.
Below are the methods to parse JSON in JavaScript:
Table of Content
- Using JSON.parse() Method
- Parsing JSON using fetch API