Chapter 9 JSON, Javascript Object, and AJAX

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
const objExample={
    name:'Lin',
    changeName: function(newName){this.name=newName}}
objExample.name
objExample.changeName("Chen");
objExample.name
document.URL;
document.querySelector("#javascript-object > h3");

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
let mr_Huang = new Person("Huang");
// object instance本身是mutable
objExample2=objExample;
objExample2.name="Lee";

// 如果建立person是常要做的事,必需要建立Person prototype,並以它產生new object instance.
const mr_Lee= new Person("Lee");

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

writeLines(
  jsonlite::toJSON(averageEX),
  con="myJsonData.json"
)

9.3.4 Fetching Data

必需使用

servr::httd()

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();

Fetch

var requestURL = 'myJsonData.json';
var exchangeRate;
fetch(requestURL).then(function(response){
    response.text().then(function(text){
      exchangeRate=text;
      })
  });

請把AJAX fetch外部伺服器的json檔例子改用fetch()函數

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.