`json()` 메서드와 `JSON.parse()` 메서드는 모두 JSON 데이터를 JavaScript 객체로 변환하지만, 그 사용 맥락과 작동 방식에는 차이가 있습니다.
일반적으로 `json()` 메서드는 `Fetch API`와 함께 사용됩니다. `fetch`를 통해 서버로부터 응답을 받으면, 이 응답은 `Response` 객체로 반환됩니다. `json()` 메서드는 이 `Response` 객체에서 JSON 데이터를 추출하고 이를 JavaScript 객체로 변환합니다.
fetch('https://api.example.com/data')
.then(response => response.json()) // Response 객체의 json() 메서드 호출
.then(data => {
console.log(data); // JSON 데이터를 JavaScript 객체로 변환한 결과
})
.catch(error => console.error('Error:', error));
```
`JSON.parse()` 메서드는 JSON 문자열을 JavaScript 객체로 변환하는 데 사용됩니다. 주로 이미 문자열 형태로 존재하는 JSON 데이터를 객체로 변환할 때 사용됩니다.
const jsonString = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: "John", age: 30, city: "New York" }
```
| DOMContentLoaded, load, onload, loadeddata, onloadeddata (2) | 2024.07.22 |
|---|---|
| scripts 유닉스 -> 윈도우 (0) | 2024.07.16 |
| forEach() - advanced (1) | 2024.07.05 |
| JSON.stringify() (0) | 2024.07.05 |
| clsx, twMerge, cn, shadcn-ui (0) | 2024.07.05 |