JavaScriptの学習[9.オブジェクトとJSONの処理]
3019 ワード
HTTP (Hypertext Transfer Protocol)
クライアントがサーバにデータを要求すると、サーバはクライアントにデータに応答します.
このタスクは主にAJAX(Asynchronous JavaScript And XML)とXHR(XML Http Request)によって行われます.
XMLを交換すると,可読性が悪く,不要なタグのためデータ量も増大するという欠点がある.
そのため、最近はJSONが多く使われています.
JSON (JavaScript Object Notation)
オブジェクト{key:value}シェイプ.
最大の利点は、プログラム言語でもプラットフォームでも使用できることです!
Object to JSON
let json = JSON.stringify(true)
console.log(json) // true
json = JSON.stringify(['apple', 'banana'])
console.log(json) // ["apple","banana"]
const rabbit = {
name: 'toto',
color: 'white',
size: null,
birthDate: new Date(),
jump: function() {
console.log(`${this.name} can jump~!!`)
}
}
json = JSON.stringify(rabbit)
console.log(json)
// {"name":"toto","color":"white","size":null,"birthDate":"2021-07-28T05:42:06.191Z"}
여기서 함수는 JSON에 포함되지 않는다는것을 알 수 있다! 추가적으로 symbol도 안된다.
json = JSON.stringify(rabbit, (key, value) => {
return key === 'name' ? 'minbro' : value
})
console.log(json)
// {"name":"minbro","color":"white","size":null,"birthDate":"2021-07-28T05:46:21.930Z"}
콜백함수를 통해 조금더 세부적으로 통제가 가능하다.
JSON to Object
json = JSON.stringify(rabbit)
const obj = JSON.parse(json)
console.log(obj)
// {name: "toto", color: "white", size: null, birthDate: "2021-07-28T05:49:39.931Z"}
rabbit.jump() // toto can jump~!!
obj.jump() // Uncaught TypeError: obj.jump is not a function
ウサギという名前のオブジェクトがJSONになったとき、関数を変換せずにデータだけを変換しますから!したがってjumpという関数は最初からjsonにはありません!
また、ウサギ上のbirthDateは別のオブジェクトなので相関関数(getYear、getDateなど…)使用できます.
しかしウサギstringgifyのjsonは、birthDateがobjectではなくstringのデータに変換されたため!
console.log(rabbit.birthDate.getDate()) // 28
console.log(obj.birthDate.getDate())
// Uncaught TypeError: obj.birthDate.getDate is not a function
しかし、parseを行う際にうまく処理すれば、使えます!const obj = JSON.parse(json, (key, value) => {
return key === 'birthDate' ? new Date(value) : value
})
console.log(obj)
// {name: "toto", color: "white", size: null, birthDate: Wed Jul 28 2021 16:34:48 GMT+0900 (한국 표준시)}
console.log(obj.brithDate.getDate()) // 28
// key가 birthDate일 경우 new Date(value)를 통해 새로 Date객체가 할당되었기 때문!
JSON Diff:JSONファイルを比較するときに便利JSON Beautifier:JSON形式が綺麗に変更
JSON Parser:JSONがObjectに変更されたときに何が起こるか
JSON Validator:JSON検証.プロンプトエラー
Reference
この問題について(JavaScriptの学習[9.オブジェクトとJSONの処理]), 我々は、より多くの情報をここで見つけました https://velog.io/@minbrother/JavaScript-공부-9テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol