Javascript6(JSON) feat.Ellie&velopert

min seung moon·2021년 3월 4일
0

Javascript

목록 보기
7/23

JSON(서버통신)

1. HTTP (HyperTextTransferProtocal)

Clinet < - 통신 -> Server
Clinet - request -> Server (요청)
Clinet < - response - Server (응답)

01. AJAX (Asynchronous Javascript And XML)

Clinet < - 통신(fetch API, JSON) -> Server
  • HyperText

    • 웹 사이트에서 이용되고 있는 hyper links 뿐만이 아니라 다양한 resource(문서나 이미지)도 포함됨
  • AJAX

    • http를 이용해서 서버에게 데이터(HyperText)를 요청해서 받아오게 하는 방법
    • 웹 페이지에서 동적으로 서버에게 데이터를 주고 받을 수 있는 기술
  • XHR (Xml Http Request) Object

    • 브라우저 API에서 제공하는 object
    • 서버에게 데이터를 요청하고 받아 올 수 있다
  • fetch() API *

    • 브라우저에 추가된 API
    • 간편하게 데이터를 주고 받을 수 있다
  • XML

    • HTML과 같은 markup language
  • JSON (JavaScriptObjectNotation)

    • 통신 format file
    • 1999 ECMAScript 3rd에서 만들어진 데이터 포멧
    • Object { key : value } JSON도 마찬가지
    • 브라우저 뿐만이아니라 모바일과 서버간의 통신 그리고 서버와의 통신을 하지 않더라도 object를 파이어 시스템에 저장 할 때 사용
    • simplest data interchange format
      => 데이터를 주고 받을 수 있는 가장 간단한 파이어 포멧
    • lightweight text-based structure
      => 텍스트 기반으로 가볍다
    • easy to read
      => 사람이 읽기도 편하다
    • key-value paris
      => key & value로 이루어진 파이어 포멧
    • used for serialization and transmission of data between the network the network connection
      => 데이터를 보통은 서버와 주고받을 때 serialization(직렬화)를 위해서 사용
      =>데이터를 전송할 때 사용
    • independent programming language and platform
      => 프로그래밍 언어나 플랫폼에 상관없이 사용될 수 있다
      Clinet - request({key:value}) -> Server (요청)
       Clinet < - response({key:value}) - Server (응답)

02. JSON 공부법

  • Object -serialize-> JSON(string)

    • object를 어떻게 serialize(직렬화)해서 Json으로 변환 할지
  • Object <-deserialize- JSON(string)

    • Serialize된 JSON 파일을 어떻게 deserialize해서 Object로 변환 할지

2. JSON (JavaScriptObjectNotation)

01. Object to JSON, JSON.stringify();

  • stringify
  • stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
  • 어떤 타입의 object를 받아와서 string으로 변환
  • string으로 만들 때 좀 더 세밀하게 통제하고 싶다면 replacer 콜백함수를 전달하면 된다
  • overloading : stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
  • Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
let json = JSON.stringify(true);
console.log(json); // "true"

json = JSON.stringify(['apple', 'banana']);
console.log(json); // ["apple', 'banana"], single quota '가 아닌 double qouta "가 표준 사항이다

const rabbit = {
	name : 'tory',
	color : 'white',
	size : null,
	birthDate : new Date(),
	sysmol : Symbol('id'),
	jump : () => {
		console.log(`${this.name} can jump!`);
	},
};
json = JSON.stringify(rabbit);
console.log(json); 
// "{"name":"tory","color":"white","size":null,"birthDate":"2021-02-02T16:54:56.602Z"}"
// 함수는 object에 있는 data가 아니기 때문에 제외된다,
// symbol 같이 js에만 있는 특별한 데이터도 포함되지 않는다

// JSON으로 변화되는것을 통제하고 싶을 때
// 배열에 key 값을 넣게되면 해당 key 값만 JSON 형식으로 변환 됨
json = JSON.stringify(rabbit, ["name"]);
console.log(json); // "{"name":"tory"}"

// callbackFn, 세밀하게 통제할 수 도 있다
json = JSON.stringify(rabbit, (key, value)=> {
console.log(`key : ${key}, value: ${value}`);
return value;
});
console.log(json);
// key : , value: [object Object]
// key : name, value: tory
// key : color, value: white
// key : size, value: null
// key : birthDate, value: 2021-02-02T16:54:56.602Z
// key : jump, value: () => {
//                    console.log(`${this.name} can jump!`);
//             }
// "{"name":"tory","color":"white","size":null,"birthDate":"2021-02-02T16:54:56.602Z"}"

json = JSON.stringify(rabbit, (key, value)=> {
console.log(`key : ${key}, value: ${value}`);
return key == 'name'?'ellie' : value;
});
console.log(json);
// "{"name":"ellie","color":"white","size":null,"birthDate":"2021-02-02T16:54:56.602Z"}"        

02. JSON to Object, JSON.parse(json)

  • parse(son), parsing
  • parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
  • json의 string data를 넣으면 어떤 타입의 object로 변환이 되고
  • optional type(전달해도 되고 안해도 되고) 콜백함수 reviver (콜백 함수인데 결과값을 뭔가 변형한다, object로 만들어지는 과정을 세밀하게 조정하고 싶을 때 사용)
  • Converts a JavaScript Object Notation (JSON) string into an object.
json = JSON.stringify(rabbit);
console.log(json);
// {"name":"tory","color":"white","size":null,"birthDate":"2021-02-02T16:54:56.602Z"}
const obj = JSON.parse(json);
console.log(obj);
// "{"name":"tory","color":"white","size":null,"birthDate":"2021-02-02T16:54:56.602Z"}"
// 함수는 포함되지 않는다

console.log(rabbit.birthDate.getDate());
// Date라는 object가 입력되어 있기에 date의 내장함수 사용가능(API)
console.log(obj.birthDate.getDate());
// Error, obj안에 있는 값은 String이기 때문에 object가 아니다

const obj = JSON.parse(json, (key,value)=>{
console.log(`key : ${key}, value: ${value}`);
return value;
});
// key : name, value: tory
// key : color, value: white
// key : size, value: null
// key : birthDate, value: 2021-02-02T16:54:56.602Z
// key : , value: [object Object]
// {name: "tory", color: "white", size: null, birthDate: "2021-02-02T16:54:56.602Z"}

// key가 birthdate의 value 값을 string이 아닌 date 객체로 전환
const obj = JSON.parse(json, (key,value)=>{
return key === 'birthDate' ? new Date(value) : value;
});
// {name: "tory", color: "white", size: null, birthDate: Wed Feb 03 2021 01:54:56 GMT+0900 (대한민국 표준시)}

console.log(obj.birthDate.getDate());
// 에러가 나지 않는다

참고 사이트

profile
아직까지는 코린이!

0개의 댓글