JavaScript의 JSON.stringify() 메서드는 JavaScript 객체를 JSON 문자열로 변환하는 데 사용됩니다. 웹 서버로 데이터를 전송할 때는 객체를 그대로 보낼 수 없기 때문에, 객체를 문자열 형태로 직렬화하는 과정이 필요하며 이때 JSON.stringify()가 매우 유용하게 활용됩니다.
JSON.stringify() 메서드는 다음과 같은 다양한 형태로 사용할 수 있습니다.
- JSON.stringify(value) : 변환할 객체를 지정합니다.
- JSON.stringify(value, replacer) : 배열이나 함수를 지정하여 특정 속성만 선택적으로 변환할 수 있습니다.
- JSON.stringify(value, replacer, space) : 들여쓰기 간격을 지정하여 가독성이 좋은 JSON 문자열을 생성할 수 있습니다.
다음은 JSON.stringify() 메서드를 활용한 전체 예제 코드입니다.
예제
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JSON.stringify()</h1>
<div class="sample"></div>
<div style="font-weight: bold;" class="result"></div>
<button class="Btn">여기를 클릭하세요</button>
<h3>
위 버튼을 클릭하면 객체가 JSON 문자열로 변환됩니다
</h3>
<script>
let sampleEle = document.querySelector(".sample");
let resultEle = document.querySelector(".result");
let obj = {name: "Rohan",sports: ["Cricket", "Football"],Country: "India"};
sampleEle.innerHTML ="Name = " +obj.name +"<br>" +" Country = " +obj.Country +
" <br>" +"sports = " +obj.sports;
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.innerHTML = JSON.stringify(obj);
});
</script>
</body>
</html>
출력 결과
페이지를 실행하면 아래와 같이 객체의 이름, 국가, 스포츠 정보가 화면에 표시됩니다.

'여기를 클릭하세요' 버튼을 클릭하면 객체가 JSON 문자열로 변환되어 아래와 같이 출력됩니다.
