JavaScript

[JavaScript] JSON 개념 정리와 활용방법 및 유용한 사이트 공유 (10)

반응형

HTTP(Hypertext Transfer Protocol)

 

클라이언트는 서버에 request를 주고 서버는 클라이언트에 response를 줍니다.

 

AJAX(Asynchronous Javascript And XML)

데이터를 주고받을 수 있는 기술, 대표적으로 XHR이라는 오브젝트가 있습니다.

최근에는 fetch() API가 나왔습니다. IE에서는 지원하지 않습니다.

 

XML이란 html과 같은 마크업언어입니다. 

 

서버와 데이터를 주고받을 때는 다양한 파일포맷을 전달 받을 수 있습니다. 요즘에 JSON을 많이 씁니다.

 

fetch나 XMLHttpRequest를 사용해서 서버와 통신할 수 있습니다.

XML은 파일의 사이즈가 커서 가독성이 좋지 않습니다.

 

JSON(JavaScript Object Notation)이 많이 쓰입니다.

Object와 마찬가지로 key 와 value로 이루어져 있습니다.

 

거의 모든 언어에서 JSON을 사용할 수 있습니다.

 

object를 serialize하면 JSON이 되고 JSON을 deserialize하면 object로 변환됩니다.

 

 

1. Object to JSON

 

stringify() 메소드를 타고 들어가면 2가지가 있는 것을 볼 수 있는데 이는 어떤 파라미터가 들어오느냐에따라 선택되며 이를 오버로딩(overloading)이라고 합니다.

 

함수가 포함된 오브젝트를 stringify 한다면 함수는 json에 포함되지 않습니다.

함수는 오브젝트에있는 데이터가 아니기 때문에 함수는 제외됩니다.

Symbol같은 자바스크립트에만있는 데이터타입 역시 json에 포함되지 않습니다.

 

그리고 stringify의 두번째 인자에 replacer를 넣으면 해당하는 값만 json으로 만들겠다는 의미입니다.

콜백함수로 더 세밀하게 조정할 수도 있습니다.

주의할 점은 콜백함수를 썼을 때 처음에는 object를 감싸고있는 최상위 객체가 출력됩니다.

let json = JSON.stringify(true);
console.log(json); // true


json =JSON.stringify(['apple', 'banana']); 
console.log(json); // ["apple", "banana"]

const rabbit = {
  name: 'tori',
  color: 'white',
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`)
  }
}

json = JSON.stringify(rabbit);
console.log(json);

json = JSON.stringify(rabbit, ["name"]);
console.log(json);

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`)
  return key === 'name' ? 'ellie' : value;
});
console.log(json);

 

 

 

2. JSON to Object

 

object를 json으로 만들고 그 json을 다시 object로 만들었기 때문에 object에는 함수가 남아있지 않습니다.

date값을 가져오기 위해서는 parse에 콜백함수를 넣어줘야합니다.

json = JSON.stringify(rabbit);
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj);
rabbit.jump(); // can jump!
obj.jump();   // Error

console.log(rabbit.birthDate.getDate()); // 29
console.log(obj.birthDate.getDate());   // Error
// obj는 string이기 때문입니다.

console.log(obj.birthDate.getDate());

 

 

 

유용한 사이트들

1. http://jsondiff.com

 

JSON Diff - The semantic JSON compare tool

 

jsondiff.com

 

2. http://jsonbeautifier.org

 

Json Beautifier - Json Formatter | Json Viewer | Json Editor

Online best free JSON Beautifier tool used as JSON editor, Json viewer, Json Validator and Json formatter to display data in a tree view and plain text.

jsonbeautifier.org

 

3. http://jsonparser.org

 

JSON Parser - Best JSON Formatter | JSON Editor

The best JSON parser online helps you to converts json to a readable. You can do json formatter, json beautifier, json viewer, json editor.

jsonParser.org

 

4. https://tools.learningcontainer.com/json-validator/

 

Best free online JSON Validator

The JSON Validator(JSONLint) helps debugging JSON data by formatting and validating JSON data, JSON String and Json Objects so that it can easily find and read errors by human beings.

tools.learningcontainer.com

 

 

반응형