Index
8. JSON
8.1 JSON 이란?
JSON(JavaScript Object Notation)은 자바스크립트에서 객체를 표현하는 형식으로 데이터를 표현한것입니다. 다른 방식에 비해 가볍고 자바스크립트와 호환성이 높아 널리 사용됩니다. 쉽게 말해 텍스트로 표현된 정보의 덩어리라고 생각하시면 됩니다.
JSON 의 기본적인 형태
{ "squadName": "슈퍼히어로", "members": [ { "name": "아이언맨", "age": 29, "본명": "토니 스타크" }, { "name": "헐크", "age": 39, "본명": "부르스 배너" } ] }
8.2 탄생 배경
프로그래머들은 언어마다 다른 표현방식 때문에 정보를 전달하는데 애를 먹습니다. 예를 들어 배열 데이터의 표현방식은 자바스크립트와 C는 다릅니다. 하지만 숫자와 문자열은 언어마다 표현방식이 같은데 이를 이용해서 만든 대표적인 데이터 폼이 xml입니다. 후에 복잡한 구조를 더 단순히 하고자 탄생한 것이 JSON 입니다.
같은 데이터를 가지는 JSON 과 xml 비교
{ "squadName": "슈퍼히어로", "members": [ { "name": "아이언맨", "age": 29, "본명": "토니 스타크" }, { "name": "헐크", "age": 39, "본명": "부르스 배너" } ] }
<?xml version="1.0" encoding="UTF-8" ?> <root> <squadName>슈퍼히어로</squadName> <members> <name>아이언맨</name> <age>29</age> <본명>토니 스타크</본명> </members> <members> <name>헐크</name> <age>39</age> <본명>부르스 배너</본명> </members> </root>
8.3 JSON 메서드
- JSON.parse(): JSON문자열을 자바스크립트 객체로 변환합니다.
- JSON.stringify() : 자바스크립트 객체를 JSON문자열로 변환합니다.
// JSON을 이용한 깊은 복사 let l = [10, 20, 30]; let a = JSON.parse(JSON.stringify(l)); a[0] = 1000; console.log(l);
JSON 응용1
const 호텔 = [{ '이름' : '하나호텔', '위치' : '제주도 제주시 001', '가격' : {'A':50000, 'B':30000, 'C':15000}, '방의개수' : 50, '예약자수' : 25, '남은방의개수' : function(){return this.방의개수 - this.예약자수} },{ '이름' : '둘호텔', '위치' : '제주도 제주시 002', '가격' : {'A':100000, 'B':60000, 'C':30000}, '방의개수' : 100, '예약자수' : 30, '남은방의개수' : function(){return this.방의개수 - this.예약자수} },{ '이름' : '셋호텔', '위치' : '제주도 제주시 003', '가격' : {'A':80000, 'B':50000, 'C':30000}, '방의개수' : 120, '예약자수' : 80, '남은방의개수' : function(){return this.방의개수 - this.예약자수} }]; console.log(호텔.filter(호텔 => (호텔.이름 =='셋호텔'))); console.log(호텔.map(호텔 => ({ '이름' : 호텔.이름, '위치' : 호텔.위치, '가격' : 호텔.가격, '방의개수' : 호텔.방의개수, '예약자수' : 호텔.예약자수, //물론 이름을 붙이는 간단한 연산 뿐만 아니라, 나라별 시간 표기법을 별도로 표시해준다던지 좀 더 복잡한 연산도 가능 '남은방의개수' : 호텔.방의개수 - 호텔.예약자수 }))); let a = [5, 4, 3, 2, 1]; console.log(a.sort((a, b) => (a - b))); console.log(호텔.sort((a, b) => (a.방의개수 - b.방의개수)));
JSON 응용2
<button onclick="renderTable(jsonData)">데이터 호출!</button> <table id="renderingDataTable"> <thead> <tr> <th onclick="sort('_id')">_id</th> <th onclick="sort('age')">age</th> <th onclick="sort('eyeColor')">eyeColor</th> <th onclick="sort('name')">name</th> <th onclick="sort('gender')">gender</th> <th onclick="sort('email')">email</th> <th onclick="sort('phone')">phone</th> </tr> </thead> <tbody></tbody> </table>
var jsonData = [ { "_id": "5e80777f673acf89c007ff91", "age": 27, "eyeColor": "green", "name": "Angelina Chang", "gender": "female", "email": "angelinachang@kangle.com", "phone": "+1 (938) 477-2821" }, { "_id": "5e80777feee717674b817fd2", "age": 25, "eyeColor": "green", "name": "Deidre Cobb", "gender": "female", "email": "deidrecobb@kangle.com", "phone": "+1 (938) 477-2824" }, { "_id": "5e80777fac368a4578dda85d", "age": 25, "eyeColor": "blue", "name": "Jolene Franks", "gender": "female", "email": "jolenefranks@kangle.com", "phone": "+1 (985) 536-3981" }, { "_id": "5e80777ff3717874cbc78e44", "age": 31, "eyeColor": "brown", "name": "Waters Hardin", "gender": "male", "email": "watershardin@kangle.com", "phone": "+1 (938) 559-2224" }, { "_id": "5e80777fe36842ea9e024fcd", "age": 34, "eyeColor": "green", "name": "Jody Chaney", "gender": "female", "email": "jodychaney@kangle.com", "phone": "+1 (878) 587-2602" }, { "_id": "5e80777fafd591f57344eb33", "age": 31, "eyeColor": "green", "name": "Ortiz Maldonado", "gender": "male", "email": "ortizmaldonado@kangle.com", "phone": "+1 (986) 509-2753" }, { "_id": "5e80777f20e48e9ada226862", "age": 25, "eyeColor": "brown", "name": "Stacy Burris", "gender": "female", "email": "stacyburris@kangle.com", "phone": "+1 (864) 577-3500" }, { "_id": "5e80777faf334f84a2c90595", "age": 33, "eyeColor": "brown", "name": "Davenport Levy", "gender": "male", "email": "davenportlevy@kangle.com", "phone": "+1 (990) 600-2700" }, { "_id": "5e80777fe9d516f0da793b7e", "age": 32, "eyeColor": "brown", "name": "Lenora Rivas", "gender": "female", "email": "lenorarivas@kangle.com", "phone": "+1 (835) 549-3209" }, { "_id": "5e80777fba91e9aeeb5ce989", "age": 35, "eyeColor": "brown", "name": "John Fischer", "gender": "female", "email": "johnfischer@kangle.com", "phone": "+1 (969) 493-3495" }, { "_id": "5e80777f63b89c8cb73127b8", "age": 23, "eyeColor": "brown", "name": "Aurora Robles", "gender": "female", "email": "aurorarobles@kangle.com", "phone": "+1 (900) 579-2424" }, { "_id": "5e80777faac1a3f50eacfbd1", "age": 20, "eyeColor": "brown", "name": "Solis Hays", "gender": "male", "email": "solishays@kangle.com", "phone": "+1 (930) 450-2123" }, { "_id": "5e80777ffd19fbf487e3957c", "age": 26, "eyeColor": "blue", "name": "Graves Jackson", "gender": "male", "email": "gravesjackson@kangle.com", "phone": "+1 (810) 556-3478" }, { "_id": "5e80777ff3bd76dd30824028", "age": 22, "eyeColor": "brown", "name": "Sharron Joyner", "gender": "female", "email": "sharronjoyner@kangle.com", "phone": "+1 (991) 418-2210" }, { "_id": "5e80777fd0f579261a830c2f", "age": 37, "eyeColor": "brown", "name": "Patty Bernard", "gender": "female", "email": "pattybernard@kangle.com", "phone": "+1 (940) 558-3881" }, { "_id": "5e80777fba4fc442f7353d84", "age": 23, "eyeColor": "brown", "name": "Sandra Foreman", "gender": "female", "email": "sandraforeman@kangle.com", "phone": "+1 (864) 500-3123" }, { "_id": "5e80777fa0897694765e4040", "age": 35, "eyeColor": "blue", "name": "Hyde Melendez", "gender": "male", "email": "hydemelendez@kangle.com", "phone": "+1 (964) 487-2694" }, { "_id": "5e80777fcf1f69b3350b06c1", "age": 40, "eyeColor": "green", "name": "Evans Wagner", "gender": "male", "email": "evanswagner@kangle.com", "phone": "+1 (944) 448-3591" }, { "_id": "5e80777fd311822be4597959", "age": 40, "eyeColor": "brown", "name": "Robinson Lynn", "gender": "male", "email": "robinsonlynn@kangle.com", "phone": "+1 (983) 564-3761" }, { "_id": "5e80777f481e9934e9fabdce", "age": 27, "eyeColor": "brown", "name": "Best Ewing", "gender": "male", "email": "bestewing@kangle.com", "phone": "+1 (950) 477-3573" }, { "_id": "5e80777fbf35be0eb2c2360a", "age": 22, "eyeColor": "green", "name": "Bird Long", "gender": "male", "email": "birdlong@kangle.com", "phone": "+1 (843) 497-2151" }, { "_id": "5e80777f37564dd622dfac58", "age": 35, "eyeColor": "green", "name": "Flynn Albert", "gender": "male", "email": "flynnalbert@kangle.com", "phone": "+1 (835) 422-2151" }, { "_id": "5e80777fa4080ca9c9a2a8f7", "age": 39, "eyeColor": "brown", "name": "Avila Chen", "gender": "male", "email": "avilachen@kangle.com", "phone": "+1 (985) 515-2235" }, { "_id": "5e80777fbf2492c1f4f6c7d2", "age": 38, "eyeColor": "green", "name": "Colette Sweet", "gender": "female", "email": "colettesweet@kangle.com", "phone": "+1 (971) 578-3870" }, { "_id": "5e80777f9dc7e14e19c042a7", "age": 39, "eyeColor": "brown", "name": "Deirdre Reilly", "gender": "female", "email": "deirdrereilly@kangle.com", "phone": "+1 (832) 546-2673" }, { "_id": "5e80777f28590be173115fdf", "age": 38, "eyeColor": "blue", "name": "Carpenter Kaufman", "gender": "male", "email": "carpenterkaufman@kangle.com", "phone": "+1 (963) 452-3989" }, { "_id": "5e80777fa4062298ee3772aa", "age": 30, "eyeColor": "green", "name": "Angela Cote", "gender": "female", "email": "angelacote@kangle.com", "phone": "+1 (868) 471-3444" }, { "_id": "5e80777fe70152016f07e965", "age": 24, "eyeColor": "blue", "name": "Carter Mueller", "gender": "male", "email": "cartermueller@kangle.com", "phone": "+1 (943) 492-2942" }, { "_id": "5e80777f162e512bf3be2b7e", "age": 35, "eyeColor": "blue", "name": "Nola Hancock", "gender": "female", "email": "nolahancock@kangle.com", "phone": "+1 (851) 523-2333" }, { "_id": "5e80777f178b7460aeb79784", "age": 35, "eyeColor": "green", "name": "Mcconnell Mosley", "gender": "male", "email": "mcconnellmosley@kangle.com", "phone": "+1 (807) 460-2627" } ]; var click = true; function sort(key){ if (click) { click = false; let sortedData = jsonData.sort((a, b) => (a[key] < b[key] ? -1 : (a[key] > b[key] ? 1 : 0))); renderTable(sortedData); } else { click = true; let sortedData = jsonData.sort((a, b) => (a[key] > b[key] ? -1 : (a[key] < b[key] ? 1 : 0))); renderTable(sortedData); } } function renderTable(data){ let tableBodyData = []; console.log('?') for (var variable of data) { tableBodyData.push(` <tr> <td>${variable._id}</td> <td>${variable.age}</td> <td>${variable.eyeColor}</td> <td>${variable.name}</td> <td>${variable.gender}</td> <td>${variable.email}</td> <td>${variable.phone}</td> </tr> `) } document.querySelector('#renderingDataTable > tbody').innerHTML = tableBodyData.join(''); }
JSON 응용 3
<button onclick="renderTable(호텔)" type="button" name="button">클릭해!!</button> <table id="rederingDataTable"> <thead> <tr> <th onclick="sort('이름')">이름</th> <th onclick="sort('위치')">위치</th> <th onclick="sort('가격')">가격</th> <th onclick="sort('방의개수')">방의개수</th> <th onclick="sort('예약자수')">예약자수</th> </tr> </thead> <tbody></tbody> </table>
var 호텔 = [{ '이름' : '하나호텔', '위치' : '제주도 제주시 001', '가격' : {'A':50000, 'B':30000, 'C':15000}, '방의개수' : 50, '예약자수' : 25, '남은방의개수' : function(){return this.방의개수 - this.예약자수} },{ '이름' : '둘호텔', '위치' : '제주도 제주시 002', '가격' : {'A':100000, 'B':60000, 'C':30000}, '방의개수' : 100, '예약자수' : 30, '남은방의개수' : function(){return this.방의개수 - this.예약자수} },{ '이름' : '셋호텔', '위치' : '제주도 제주시 003', '가격' : {'A':80000, 'B':50000, 'C':30000}, '방의개수' : 120, '예약자수' : 80, '남은방의개수' : function(){return this.방의개수 - this.예약자수} }]; function sort(name){ let 정렬된호텔 = 호텔.sort((a, b) => (b[name] - a[name])); renderTable(정렬된호텔); } function renderTable(호텔기본값){ let tableBody = []; // JSON.stringify({ x: 5, y: 6 }) for (var variable of 호텔기본값) { tableBody.push(` <tr> <td>${variable.이름}</td> <td>${variable.위치}</td> <td>${JSON.stringify(variable.가격)}</td> <td>${variable.방의개수}</td> <td>${variable.예약자수}</td> </tr> `); } document.querySelector('#rederingDataTable > tbody').innerHTML = tableBody.join(''); }