JSON.parse()
and .json()
are both methods used to work with JSON data in JavaScript, but they serve different purposes and are used in different contexts.
JSON.parse()
JSON.parse()
is a built-in JavaScript function that parses a JSON string and converts it into a JavaScript object.- It can be used to convert JSON data received from various sources (e.g., from an API, from local storage) into a format that can be manipulated and used within a JavaScript program.
- Unlike
.json()
,JSON.parse()
is not specific to any particular API or context; it can be used anywhere in a JavaScript program where JSON data needs to be parsed.
const jsonString = '{"name": "John", "age": 30}';
const data = JSON.parse(jsonString);
console.log(data.name); // Output: John
console.log(data.age); // Output: 30
.json()
.json()
is a method typically used with thefetch()
API in modern web development. It is used to extract JSON data from a response object returned by thefetch()
function.- It parses the JSON response body and returns a promise that resolves to the parsed JSON data.
- This method is specific to working with the
fetch()
API and is not available in other contexts.
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));