JSON 클래스 stringfy(), parse()

냐옹·2024년 5월 15일
0

JS

목록 보기
5/6

개요

  • 두 메서드 모두 js에서 json데이터를 다루기 위해서 사용하는 주요 메서드들이다.

JSON.stringfy() - 직렬화 serialize

  • js객체를 json문자열로 변환하는 메서드다. (json -> 문자열)
  • api 호출에서 데이터를 서버로 보낼때 주로 사용한다.
  • 이렇게 만들어진 api를 사용할 경우에 우리는 문자열을 받게 된다.
const user = {
  name: "John",
  age: 30,
  isAdmin: true
};

const jsonString = JSON.stringify(user);
console.log(jsonString); // {"name":"John","age":30,"isAdmin":true}

이렇게 받아온 jsonString은 문자열이기 때문에 사용하려면 json객체로 만들어주어야 한다.

하단은 post 요청을 보내는 것인데, 보낼때 json을 직렬화 serialize (문자열화) 하고 있다.

const data = {
  name: "John",
  age: 30
};

fetch('https://api.example.com/user', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

JSON.parse() - 역직렬화 deserialize

  • 문자열(JSON형태의) 을 JS JSON 객체로 변환해주는 메서드이다.
  • API 호출을 해서 서버로부터 받은 문자열JSON을 JS JSON객체로 변환할때 주로 사용한다.
const jsonString = '{"name":"John","age":30,"isAdmin":true}';

const user = JSON.parse(jsonString);
console.log(user.name); // John

api 응답으로부터 받은 문자열json데이터를 js json객체로 변환하는 예시를 살펴보자.

fetch('https://api.example.com/user')
  .then(response => response.json()) // 여기서 JSON.parse가 내부적으로 호출됩니다
  .then(data => {
    console.log(data); // JavaScript 객체로 변환된 데이터
  })
  .catch(error => {
    console.error('Error:', error);
  });

추가

그럼 response.json은 어떤 동작을 할까.
이것은 js의 fetch api에서 제공하는 메서드로, http 응답(Response) 객체의 본문을 JSON형식으로 파싱하여 JS객체로 변환해주는 역할을 한다.
이 메서드는 Promise를 반환한다.

Fetch api와 response.json()

Fetch api를 사용하면 네트워크 요청을 쉽게 보낼 수 있다. fetch 함수는 네트워크 요청을 보내고 response 객체를 반환한다. 이 response 객체에는 서버로부터 받은 데이터가 포함되어있다.
만약에 서버가 json형식의 데이터를 반환하면, 이를 js 객체로 변환하기 위해서 response.json() 메서드를 사용한다.

예시

fetch('https://api.example.com/data')
  .then(response => response.json()) // 응답을 JSON으로 파싱
	// json() 메서드는 promise를 반환하고 이 promise는 파싱된 js 객체로 해결된다. 
  .then(data => {
    console.log(data); // JavaScript 객체로 변환된 데이터 사용
  })
  .catch(error => {
    console.error('Error:', error);
  });

응답코드 에러 처리를 더하면

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      // HTTP 응답 상태 코드 확인
      if (response.status >= 400 && response.status < 500) {
        // 400번대 에러 (클라이언트 에러)
        throw new Error(`Client error: ${response.status} - ${response.statusText}`);
      } else if (response.status >= 500 && response.status < 600) {
        // 500번대 에러 (서버 에러)
        throw new Error(`Server error: ${response.status} - ${response.statusText}`);
      } else {
        // 기타 에러
        throw new Error(`Unexpected error: ${response.status} - ${response.statusText}`);
      }
    }
    return response.json(); // 응답을 JSON으로 파싱
  })
  .then(data => {
    console.log(data); // JavaScript 객체로 변환된 데이터 사용
  })
  .catch(error => {
    // 에러 처리
    console.error('Error:', error.message);
  });

추가로 저기에서 예를 들어서 api호출을 많이 하는 컴포넌트이다 라고 하면 일일히 다 분기문을 적는 건 귀찮고, 코드 중복이 많이 된다. 그러면 이런 식으로 따로 함수로 빼자

const handleError = (status) => {
    const errorMessages = {
      400: "bad request",
      404: "not found",
      500: "server internal error",
    };
    throw new Error(errorMessages[status] || "other error");
  };

0개의 댓글