JavaScript WEB - JSON

김재환·2023년 11월 14일

JavaScriptWEB

목록 보기
7/27

fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.text())
.then((result) => {console.log(result)})

[{},{}]형태로 반환

JavaScript Object Notation 정보를 교환하기 위해 사용하기 위해 만들어진 데이터포맷
자바스크립트 문법을 빌려 만든 데이터 포맷

fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.text())
.then((result) => {console.log(typeof result)})

console.log(typeof result) = string

fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.text())
.then((result) => {
const users = JSON.parse(result)
console.log(users.length);
users.forEach((user) =>{
console.log(user.name)
});
});

JSON이라는 객체에 parse()라는 메소드를 사용하면 String type 데이터를 자바스크립트 객체로 변환할수 있어

// fetch('https://learn.codeit.kr/api/topics')
// .then((response) => response.text())
// .then((result) => { console.log(result) }) ;

// 일단 이 코드를 주석 해제하고, 아래 코드를 주석 처리해서
//어떤 JSON 데이터가 오는지 확인하세요

fetch('https://learn.codeit.kr/api/topics')
.then((response) => response.text())
.then((result) => {
const topics = JSON.parse(result)// 여기에 코드를 작성하세요
const beginnerLevelTopics = topics.filter((topic) => topic.difficulty === '초급');
console.log(beginnerLevelTopics);
});
beginnerLevelTopics에 배열의 형태로 저장

JSON 데이터가 코드에서 result 파라미터로 넘어올 때는 그 데이터 타입이 String 이기 때문에 자바스크립트 객체로 변환을 해줘야 합니다.
이를 위해서 자바스크립트의 기본 내장 객체인 JSON이라는 객체의 parse메소드의 파라미터로 해당 JSON데이터를 넣고 실행하면 돼요
그럼 JSON 데이터에서 현재 배열로 표현돼있는 부분이, 실제로 자바스크립트 배열(객체)로 변환되어서 코드 상에서 자유롭게 사용할 수 있게 됩니다. 이렇게 string 타입의 JSON 데이터를 실제 자바스크립트 객체로 변환하는 것을 Deserialization, 우리말로는 역직렬화라고 합니다. 아주 중요한 개념이니까 잘 기억해 주세요.

Deserialization 이후의 나머지 코드를 보면, topics 배열의 filter 메소드를 사용해서 각 요소의 "difficulty" 프로퍼티(토픽의 난이도) 값이 '초급'에 해당하는 것들만 추출해서 만든 새로운 배열을 리턴하고 있습니다. 그리고 마지막에 초급 토픽들로 이루어진 배열을 출력하고 있네요.

개발자가 되면 이번 과제에서 한 것처럼 리스폰스의 내용으로 오는 JSON 데이터를 다뤄야할 경우가 많습니다. 그리고 이때는 보통 string 타입의 JSON 데이터를 자바스크립트 객체로 만드는 Deserialization을 먼저 수행한다는 사실, 꼭 기억하세요.

profile
안녕하세요

0개의 댓글