JavaScript와 JSON: 완벽한 가이드 2026
JavaScript에서 JSON을 마스터하세요. JSON.parse(), JSON.stringify(), 오류 처리, fetch API 및 모범 사례에 대한 완벽한 가이드입니다.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# JavaScript와 JSON: 완벽한 가이드 2026
JSON(JavaScript Object Notation)은 JavaScript에서 유래했지만 단순한 JavaScript 객체가 아닙니다. 이 종합 가이드는 JavaScript에서 JSON 작업의 모든 것을 다룹니다.
JavaScript JSON 기본
JavaScript는 JSON 작업을 위한 두 가지 주요 메서드를 제공합니다:
- JSON.parse(): JSON 문자열 → JavaScript 객체
- JSON.stringify(): JavaScript 객체 → JSON 문자열
JSON.parse() - JSON 파싱
기본 사용
// JSON 문자열
const jsonString = '{"name":"홍길동","age":30,"city":"서울"}';
// JavaScript 객체로 파싱
const user = JSON.parse(jsonString);
console.log(user.name); // 출력: 홍길동
console.log(user.age); // 출력: 30
배열 파싱
const jsonArray = '[{"id":1,"name":"김철수"},{"id":2,"name":"이영희"}]';
const users = JSON.parse(jsonArray);
users.forEach(user => {
console.log(ID: ${user.id}, 이름: ${user.name});
});
중첩된 객체
const jsonData =
{
"company": "테크 이노베이션",
"address": {
"street": "테헤란로 123",
"city": "서울",
"country": "한국"
},
"employees": [
{"name": "김철수", "role": "개발자"},
{"name": "이영희", "role": "디자이너"}
]
}
;
const company = JSON.parse(jsonData);
console.log(company.address.city); // 서울
console.log(company.employees[0].name); // 김철수
reviver 함수 사용
reviver 함수는 파싱 중 값을 변환할 수 있습니다:
const jsonString =
{
"name": "홍길동",
"createdAt": "2026-01-16T10:30:00.000Z",
"age": 30
}
;
// Date 객체로 변환
const user = JSON.parse(jsonString, (key, value) => {
if (key === 'createdAt') {
return new Date(value);
}
return value;
});
console.log(user.createdAt instanceof Date); // true
console.log(user.createdAt.getFullYear()); // 2026
JSON.stringify() - JSON 직렬화
기본 사용
const user = {
name: "홍길동",
age: 30,
city: "서울",
skills: ["JavaScript", "Python", "Go"]
};
// JSON 문자열로 변환
const jsonString = JSON.stringify(user);
console.log(jsonString);
// 출력: {"name":"홍길동","age":30,"city":"서울","skills":["JavaScript","Python","Go"]}
예쁘게 출력 (Pretty Print)
// 들여쓰기 2칸
const formatted = JSON.stringify(user, null, 2);
console.log(formatted);
결과:
{
"name": "홍길동",
"age": 30,
"city": "서울",
"skills": [
"JavaScript",
"Python",
"Go"
]
}
replacer 함수 사용
특정 속성 제외 또는 변환:
const user = {
name: "홍길동",
password: "secret123",
age: 30,
email: "hong@example.com"
};
// 비밀번호 제외
const json = JSON.stringify(user, (key, value) => {
if (key === 'password') {
return undefined; // 제외
}
return value;
}, 2);
console.log(json);
// password 필드가 없음
replacer 배열 사용
특정 속성만 포함:
const user = {
name: "홍길동",
age: 30,
email: "hong@example.com",
password: "secret",
address: "서울"
};
// name과 email만 포함
const json = JSON.stringify(user, ['name', 'email'], 2);
console.log(json);
결과:
{
"name": "홍길동",
"email": "hong@example.com"
}
JSON vs JavaScript 객체
주요 차이점
| 기능 | JavaScript 객체 | JSON |
|------|-----------------|------|
| 키 | 따옴표 선택 | 큰따옴표 필수 |
| 문자열 | 작은/큰따옴표 | 큰따옴표만 |
| 함수 | 허용 | 허용 안 됨 |
| undefined | 허용 | 허용 안 됨 |
| 주석 | 허용 | 허용 안 됨 |
| 후행 쉼표 | 허용 | 허용 안 됨 |
JavaScript 객체
const jsObject = {
name: '홍길동', // 작은따옴표 OK
greet() { // 메서드 OK
return '안녕하세요';
},
value: undefined // undefined OK
};
유효한 JSON
{
"name": "홍길동"
}
Fetch API와 JSON
GET 요청
// API에서 JSON 가져오기
fetch('https://api.example.com/users')
.then(response => response.json()) // JSON 자동 파싱
.then(users => {
users.forEach(user => {
console.log(user.name);
});
})
.catch(error => console.error('오류:', error));
Async/Await 사용
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(HTTP 오류! 상태: ${response.status});
}
const users = await response.json();
return users;
} catch (error) {
console.error('오류:', error);
return [];
}
}
// 사용
const users = await getUsers();
console.log(users);
POST 요청
const newUser = {
name: "홍길동",
email: "hong@example.com",
age: 30
};
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log('성공:', data))
.catch(error => console.error('오류:', error));
PUT/PATCH 요청
async function updateUser(userId, updates) {
const response = await fetch(https://api.example.com/users/${userId}, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updates)
});
return await response.json();
}
// 사용
const updated = await updateUser(1, { age: 31 });
console.log(updated);
오류 처리
JSON.parse() 오류
const invalidJson = '{"name": "홍길동", "age": 30,}'; // 후행 쉼표
try {
const data = JSON.parse(invalidJson);
} catch (error) {
console.error('JSON 파싱 오류:', error.message);
// JSON 파싱 오류: Unexpected token } in JSON at position 34
}
안전한 JSON 파싱
function safeJsonParse(jsonString, fallback = null) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('JSON 파싱 실패:', error);
return fallback;
}
}
// 사용
const data = safeJsonParse('유효하지 않은 JSON', {});
console.log(data); // {}
Fetch 오류 처리
async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
// HTTP 오류 확인
if (!response.ok) {
throw new Error(HTTP ${response.status}: ${response.statusText});
}
// Content-Type 확인
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('응답이 JSON이 아닙니다');
}
return await response.json();
} catch (error) {
if (error instanceof TypeError) {
console.error('네트워크 오류:', error);
} else if (error instanceof SyntaxError) {
console.error('유효하지 않은 JSON:', error);
} else {
console.error('오류:', error);
}
throw error;
}
}
localStorage와 JSON
데이터 저장
const user = {
name: "홍길동",
age: 30,
preferences: {
theme: "dark",
language: "ko"
}
};
// 객체를 JSON으로 저장
localStorage.setItem('user', JSON.stringify(user));
데이터 불러오기
// JSON 문자열 가져오기 및 파싱
const userJson = localStorage.getItem('user');
const user = JSON.parse(userJson);
console.log(user.name); // 홍길동
console.log(user.preferences.theme); // dark
헬퍼 함수
const storage = {
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (error) {
console.error('저장 오류:', error);
return false;
}
},
get(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
console.error('불러오기 오류:', error);
return defaultValue;
}
},
remove(key) {
localStorage.removeItem(key);
}
};
// 사용
storage.set('settings', { theme: 'dark', lang: 'ko' });
const settings = storage.get('settings', { theme: 'light' });
toJSON() 메서드
사용자 정의 직렬화:
class User {
constructor(name, password, email) {
this.name = name;
this.password = password;
this.email = email;
}
// JSON 직렬화 사용자 정의
toJSON() {
return {
name: this.name,
email: this.email
// password는 제외
};
}
}
const user = new User('홍길동', 'secret123', 'hong@example.com');
const json = JSON.stringify(user, null, 2);
console.log(json);
결과:
{
"name": "홍길동",
"email": "hong@example.com"
}
Deep Clone
JSON을 사용한 깊은 복사:
const original = {
name: "홍길동",
address: {
city: "서울",
zipCode: "12345"
},
skills: ["JavaScript", "Python"]
};
// 깊은 복사
const clone = JSON.parse(JSON.stringify(original));
// 복사본 수정
clone.address.city = "부산";
clone.skills.push("Go");
console.log(original.address.city); // 서울 (변경 안 됨)
console.log(clone.address.city); // 부산
주의사항:
- 함수는 손실됨
- undefined는 손실됨
- Date는 문자열이 됨
- Map, Set은 빈 객체가 됨
스트리밍 JSON
Fetch Stream 사용
async function streamJsonArray(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// 완전한 JSON 객체 처리
const lines = buffer.split('\n');
buffer = lines.pop(); // 불완전한 줄 유지
for (const line of lines) {
if (line.trim()) {
const data = JSON.parse(line);
console.log(data);
}
}
}
}
모범 사례
1. 항상 try-catch 사용
// 좋음
try {
const data = JSON.parse(jsonString);
} catch (error) {
console.error('파싱 오류:', error);
}
// 나쁨
const data = JSON.parse(jsonString); // 오류 발생 가능
2. Content-Type 확인
async function fetchJson(url) {
const response = await fetch(url);
const contentType = response.headers.get('content-type');
if (!contentType?.includes('application/json')) {
throw new Error('JSON 응답이 아닙니다');
}
return await response.json();
}
3. 민감한 데이터 제외
const user = {
name: "홍길동",
password: "secret",
token: "abc123"
};
// replacer로 민감한 필드 제거
const safeJson = JSON.stringify(user, (key, value) => {
if (['password', 'token'].includes(key)) {
return undefined;
}
return value;
});
4. 타입 검증
function isValidUser(data) {
return (
typeof data === 'object' &&
data !== null &&
typeof data.name === 'string' &&
typeof data.age === 'number' &&
typeof data.email === 'string'
);
}
const data = JSON.parse(jsonString);
if (isValidUser(data)) {
// 안전하게 사용
console.log(data.name);
}
성능 최적화
대용량 데이터
// 나쁨: 모든 데이터를 한 번에 처리
const hugeArray = JSON.parse(hugeJsonString);
hugeArray.forEach(item => process(item));
// 좋음: 청크로 처리
async function processInChunks(data, chunkSize = 100) {
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
await processChunk(chunk);
}
}
메모이제이션
const parseCache = new Map();
function cachedParse(jsonString) {
if (parseCache.has(jsonString)) {
return parseCache.get(jsonString);
}
const result = JSON.parse(jsonString);
parseCache.set(jsonString, result);
return result;
}
일반적인 오류
1. 후행 쉼표
// 잘못됨
const json = '{"name": "홍길동",}';
// 올바름
const json = '{"name": "홍길동"}';
2. 작은따옴표
// 잘못됨
const json = "{'name': '홍길동'}";
// 올바름
const json = '{"name": "홍길동"}';
3. undefined 값
const obj = { name: "홍길동", age: undefined };
const json = JSON.stringify(obj);
console.log(json); // {"name":"홍길동"} - age가 생략됨
4. 순환 참조
const obj = { name: "홍길동" };
obj.self = obj; // 순환 참조
try {
JSON.stringify(obj); // TypeError!
} catch (error) {
console.error('순환 참조 오류');
}
결론
JavaScript와 JSON은 완벽한 조합입니다. JSON.parse()와 JSON.stringify()를 마스터하고, 오류를 적절히 처리하며, 모범 사례를 따르면 JavaScript 애플리케이션에서 JSON을 효과적으로 작업할 수 있습니다.
주요 요점:- ✓ JSON.parse()로 파싱, JSON.stringify()로 직렬화
- ✓ 항상 오류 처리 사용
- ✓ Fetch API와 함께 JSON 사용
- ✓ replacer/reviver로 사용자 정의
- ✓ localStorage에 객체 저장
- ✓ Content-Type 검증
행복한 JavaScript JSON 코딩하세요!
관련 글
JSON이란 무엇인가? JavaScript Object Notation 완벽 가이드
JSON(JavaScript Object Notation)의 기본 개념부터 실제 활용까지. 웹 개발의 필수 데이터 형식인 JSON을 완벽하게 이해해보세요.
Python과 JSON: 완벽한 가이드 2026
Python에서 JSON을 마스터하세요. json 모듈, 파싱, 직렬화, 파일 작업 및 고급 기술에 대한 종합 가이드입니다.
JSON API와 REST 서비스: 현대 웹 개발의 핵심
JSON API와 REST 서비스의 모든 것을 배워보세요. RESTful 설계 원칙, 실용적인 예제, 모범 사례까지 완벽 정리.