JSON 객체를 생성하고 사용하는 방법을 JavaScript로 간단히 설명하겠습니다. JSON 객체는 JavaScript에서 데이터를 구조화하고 교환하는 데 자주 사용됩니다.
1. JSON 객체 생성
// 1. JavaScript 객체로 JSON 생성
const person = {
name: "John",
age: 30,
isStudent: false,
skills: ["JavaScript", "React", "Node.js"],
address: {
city: "Seoul",
country: "Korea"
}
};
// 2. JSON 문자열로 생성
const personJSON = `{
"name": "John",
"age": 30,
"isStudent": false,
"skills": ["JavaScript", "React", "Node.js"],
"address": {
"city": "Seoul",
"country": "Korea"
}
}`;
// 1. JavaScript 객체로 JSON 생성
const person = {
name: "John",
age: 30,
isStudent: false,
skills: ["JavaScript", "React", "Node.js"],
address: {
city: "Seoul",
country: "Korea"
}
};
// 2. JSON 문자열로 생성
const personJSON = `{
"name": "John",
"age": 30,
"isStudent": false,
"skills": ["JavaScript", "React", "Node.js"],
"address": {
"city": "Seoul",
"country": "Korea"
}
}`;
// 1. JavaScript 객체로 JSON 생성 const person = { name: "John", age: 30, isStudent: false, skills: ["JavaScript", "React", "Node.js"], address: { city: "Seoul", country: "Korea" } }; // 2. JSON 문자열로 생성 const personJSON = `{ "name": "John", "age": 30, "isStudent": false, "skills": ["JavaScript", "React", "Node.js"], "address": { "city": "Seoul", "country": "Korea" } }`;
2. JSON 객체 사용
1) JSON 문자열을 JavaScript 객체로 변환
const personObject = JSON.parse(personJSON);
console.log(personObject.name); // "John"
console.log(personObject.skills[0]); // "JavaScript"
const personObject = JSON.parse(personJSON);
console.log(personObject.name); // "John"
console.log(personObject.skills[0]); // "JavaScript"
const personObject = JSON.parse(personJSON); console.log(personObject.name); // "John" console.log(personObject.skills[0]); // "JavaScript"
2) JavaScript 객체를 JSON 문자열로 변환
const jsonString = JSON.stringify(person);
console.log(jsonString);
// 출력: {"name":"John","age":30,"isStudent":false,"skills":["JavaScript","React","Node.js"],"address":{"city":"Seoul","country":"Korea"}}
const jsonString = JSON.stringify(person);
console.log(jsonString);
// 출력: {"name":"John","age":30,"isStudent":false,"skills":["JavaScript","React","Node.js"],"address":{"city":"Seoul","country":"Korea"}}
const jsonString = JSON.stringify(person); console.log(jsonString); // 출력: {"name":"John","age":30,"isStudent":false,"skills":["JavaScript","React","Node.js"],"address":{"city":"Seoul","country":"Korea"}}
3. JSON 데이터 접근 및 수정
// 객체의 속성 접근
console.log(person.name); // "John"
console.log(person.address.city); // "Seoul"
// 속성 수정
person.age = 31;
person.skills.push("TypeScript");
console.log(person);
// {name: "John", age: 31, isStudent: false, skills: Array(4), address: {…}}
// 객체의 속성 접근
console.log(person.name); // "John"
console.log(person.address.city); // "Seoul"
// 속성 수정
person.age = 31;
person.skills.push("TypeScript");
console.log(person);
// {name: "John", age: 31, isStudent: false, skills: Array(4), address: {…}}
// 객체의 속성 접근 console.log(person.name); // "John" console.log(person.address.city); // "Seoul" // 속성 수정 person.age = 31; person.skills.push("TypeScript"); console.log(person); // {name: "John", age: 31, isStudent: false, skills: Array(4), address: {…}}
4. JSON 데이터를 활용한 API 호출 예제
Fetch를 사용해 JSON 데이터 가져오기
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // JSON 문자열을 객체로 변환
.then(data => {
console.log(data.title); // 가져온 데이터의 제목 출력
})
.catch(error => console.error('Error:', error));
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // JSON 문자열을 객체로 변환
.then(data => {
console.log(data.title); // 가져온 데이터의 제목 출력
})
.catch(error => console.error('Error:', error));
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) // JSON 문자열을 객체로 변환 .then(data => { console.log(data.title); // 가져온 데이터의 제목 출력 }) .catch(error => console.error('Error:', error));
Fetch를 사용해 JSON 데이터 전송
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: "My Post",
body: "This is a sample post",
userId: 1
})
})
.then(response => response.json())
.then(data => {
console.log(data); // 서버에서 반환된 데이터 출력
})
.catch(error => console.error('Error:', error));
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: "My Post",
body: "This is a sample post",
userId: 1
})
})
.then(response => response.json())
.then(data => {
console.log(data); // 서버에서 반환된 데이터 출력
})
.catch(error => console.error('Error:', error));
fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: "My Post", body: "This is a sample post", userId: 1 }) }) .then(response => response.json()) .then(data => { console.log(data); // 서버에서 반환된 데이터 출력 }) .catch(error => console.error('Error:', error));
요약
- JSON.parse(): JSON 문자열 → JavaScript 객체로 변환
- JSON.stringify(): JavaScript 객체 → JSON 문자열로 변환
- fetch API: JSON 데이터를 주고받을 때 사용
JSON은 데이터를 구조화하고 네트워크 간 데이터를 교환할 때 유용합니다!