How to Parse JSON in JavaScript ?
Last Updated :
30 Apr, 2024
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:
Using JSON.parse() Method
In this approach, The JSON.parse() method is used to parse JSON strings into JavaScript objects. It's straightforward to use, accepting a JSON string as input and returning a corresponding JavaScript object. However, it's important to note its limitations, such as disallowing trailing commas and single quotes.
Example: The code below shows How to Parse JSON in JavaScript using JSON.parse() Method.
JavaScript
const jsonString = '{"name": "Geeks", "age": 30}';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj.name);
console.log(jsonObj.age);
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.
JavaScript
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' }
}