Chapter 9 JSON, Javascript Object, and AJAX
9.1 教材
9.2 學習主題
What is JSON?
fetch data or send data in the internet.
Conversion between JSON and JS Object.
JSON Object.
JSON exists as a string — useful when you want to transmit data across a network.
It needs to be converted to a native JavaScript object when you want to access the data.
- JavaScript provides a global JSON object that has methods available for converting between the two.
9.3 主題內容
9.3.1 Javascript Object
- JS object
JS裡頭有property或method的物件都叫Javascript object。
- JS object prototype
function Person(familyName){
this.name=familyName;
this.changeName=function(newName){this.name=newName}
}
- JS Object Prototype usage
9.3.2 What is JSON?
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax.
- JSON is purely a data format — it contains only properties, no methods.
JSON
{
"name": "Lin",
"courses_taking": ["Micro", "Macro"]
}
JS Object
{
name:'Lin',
changeName: function(newName){this.name=newName}
}
Assign to an object in JS
var objFromJSON={
"name": "Lin",
"courses_taking": ["Micro", "Macro"]
}
var objFromJSObject={
name:'Lin',
changeName: function(newName){this.name=newName}
}
JSON直接寫在Javascript裡會形成JS object。兩者的差異要當JSON由外部引入時才看得出來。
the slight difference: JSON take
only double quotes.
no function (aka method in JS Object).
name:value pair with names double-quoted.
9.3.3 外部引入JSON
下面代表你用R做了一些事
library(dplyr)
exDataPost80s <- readr::read_csv("https://www.dropbox.com/s/rc6t40gsxduysz6/exDataPost80s.csv?dl=1")
exDataPost80s %>%
group_by(幣別) %>%
summarise(
平均匯率=mean(匯率, na.rm=T)
) -> averageEX
最後把它以JSON形式存在myJsonData.json
9.3.4 Fetching Data
AJAX
var requestURL = 'myJsonData.json'
//設定準備使用的GET instance
const requestMyJson = new XMLHttpRequest();
requestMyJson.open('GET', requestURL);
requestMyJson.responseType = 'json';
var exchangeRate
//Asynchronous communication
requestMyJson.onload = function() {
exchangeRate = requestMyJson.response;
}
//送出請求
requestMyJson.send();
Fetch外部伺服器的json檔:
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; //如前面已出現var requestURL, var可不寫
//設定準備使用的GET instance
const request2 = new XMLHttpRequest();
request2.open('GET', requestURL);
request2.responseType = 'json';
var superHeroes
//Asynchronous communication
request2.onload = function() {
superHeroes = request2.response;
}
//送出請求
request2.send();
9.3.5 Conversion between JSON and JS Object.
The conversion between JSON and JS object are mainly through the built-in JSON object in Javascript.