티스토리 뷰
참고 - 같은 폴더 위치를 기준으로 작성했습니다.
|- index.html
|- main.js
|- data.json
1) Json 파일을 읽어오는 방법 - fetch()
data.json파일 ( 보통은 엄청 길겠지만 테스트로 간단하게 작성했다. )
{
"list":[
{
"number" : 25,
"name" : "Kim"
},
{
"number" : 34,
"name" : "Lee"
}
]
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<title>제목</title>
</head>
<body>
<div class="json-wrapper">
<ul id="jsonListWrap"></ul>
</div>
</body>
main.js
window.onload = () => {
fetch("data.json")
.then((response) => response.json())
.then((json) => {
data = json.list;
const jsonListWrap = document.getElementById("jsonListWrap");
data.forEach(el => {
jsonListWrap.innerHTML += `
<li> 번호 : ${el.number}</li>
<li> 이름 : ${el.name}</li>
`;
});
});
}
2) Json 데이터 html에 출력하고 데이터 수정, 추가
index.html
버튼을 누르면 수정된 데이터가 적용시키는 방식으로 html에서 직접 데이터를 작성할 수 있도록 textarea태그를 사용했습니다.
그냥 보여주는 것만이 목적이라면 <pre>태그를 사용해도 됩니다.
<div class="json-wrapper">
<textarea id="jsonList" rows="20" cols="50"></textarea>
<button onclick="jsonApplyBtn()" class="applyBtn">Apply</button>
</div>
main.js
1. js파일에 선언된 json형태의 객체안 배열 데이터 출력하기
document.getElementById(...)는 해당 요소가 DOM에 있어야만 제대로 찾을 수 있기 때문에 window.onload 안에 작성했다.
즉, window.onload 안에서 실행하거나, 스크립트를 <body> 맨 아래에 두는 게 안전함.
window.onload = () => {
const jsonDataList = document.getElementById("jsonDataList");
jsonDataList.textContent = JSON.stringify(jsonData, null, 2);
}
let jsonData = {
"list":[
{
"number" : 25,
"name" : "Kim"
},
{
"number" : 34,
"name" : "Lee"
}
]
}
2. onclick 함수
button태그에서 바로 onclick으로 함수를 호출했기 때문에 onclick함수는 전역에 작성했다.
1. 키 값을 수정할 수 없도록 Object.prototype.hasOwnProperty를 사용해 객체가 해당 키를 가지고 있는지 체크.
* Object.prototype를 사용한 이유? data가 비어있는 상태 null인 경우에 hasOwnProperty가 없어서 에러가 날 수 있음.
2. 타입 체크
: 잘못된 타입의 값을 받는 것을 방지하기 위해 typeof 를 사용해서 조건을 추가. [예] number : "11" (X)
function jsonApplyButton() {
try {
const newJsonInput = jsonDataList.value;
const newData = JSON.parse(newJsonInput);
// 객체에 list가 있고, 그 안이 배열인지 확인
const isValid =
newData &&
Array.isArray(newData.list) &&
newData.list.every((item) =>
Object.prototype.hasOwnProperty.call(item, "number") &&
Object.prototype.hasOwnProperty.call(item, "name") &&
typeof item.number === "number" &&
typeof item.name === "string"
);
if(!isValid) {
alert("잘못된 구조입니다.");
jsonDataList.textContent = JSON.stringify(jsonData, null, 2);
return;
}
jsonData = newData;
console.log("jsonData:", jsonData);
alert("적용되었습니다.");
}catch(error){
alert("잘못된 JSON 형식입니다.");
console.log(error);
}
}
=> 데이터 삭제도 잘 적용된다.
사용한 문법 정리
JSON.stringify() 문법
JSON.stringify(value, replacer, space);
- value : JSON으로 변환할 값 (예: 객체, 배열)
- replacer : 어떤 값을 필터링하거나 가공할지 결정하는 함수 or 배열 → 대부분 null로 둠.
- space : 들여쓰기 간격. 숫자(n)면 n칸, 문자열이면 그걸로 들여쓰기
splice(index, deleteCount) 문법
array.splice(시작인덱스, 삭제할개수)
- index : 삭제를 시작할 위치
- 삭제할개수(숫자) : 그 위치부터 몇 개를 삭제할지를 나타낸다.
.every()
배열 안의 모든 요소가 조건을 만족하는지 검사하는 메서드.
하나라도 틀리면 false, 전부 맞으면 true를 반환한다.
array.every(callback)
'JavaScript' 카테고리의 다른 글
[JS] reduce 메서드 (0) | 2024.09.25 |
---|---|
[비동기]Promise와 async/await의 차이 (2) | 2024.09.20 |
[Javascript]EndsWith 메서드 (0) | 2024.09.09 |
[Javascript] exec() 메서드란? (+ Match 함수 / MatchAll 함수) (4) | 2024.09.09 |
[노마드 바닐라JS 챌린지] Day.13 Geolocation (0) | 2023.05.30 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- create react app
- 노마드
- React
- slice
- 타입스크립트
- 리액트네이티브
- 프로젝트회고록
- TypeScript
- 카카오로그인
- 오버로딩
- nomard
- 재귀함수
- CLI
- useState
- 챌린지1일차
- splice
- ts
- Async
- 프로그래머스
- Cleanup
- ReactJS
- 티스토리챌린지
- 자바스크립트
- useEffect
- 리액트
- 오블완
- await
- NPM
- props
- overloading
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
글 보관함