본문 바로가기

JavaScript/Web Development

[JavaScript] 객체 변환 JSON 데이터

개발자 도구에서 JSON 데이터의 데이터 타입을 확인하면, 

response.text() 에 따라 string(문자열) 인 것을 확인할 수 있음. 그러나 string 타입의 객체로는 데이터를 다루는데 어려움이 있어서, JSON 객체를 다시 자바스크립트 객체로 변환하는 과정이 필요함.

 

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

JSON 객체에 parse 라는 메소드를 사용하면, string타입의 JSON 객체를 자바스크립트 객체로 변환할 수 있음.

 

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)
    });
  });

forEach 메소드는 배열의 각 요소를 순회하며 매번 파라미터로 받은 함수를 실행함. 

 

배열의 총길이 10과 10명의 이름이 출력