目錄javascript
JSON 是一種按照JavaScript對象語法的數據格式,由 Douglas Crockford 推廣。雖然它是基於 JavaScript 語法,但它獨立於JavaScript,這也是爲何許多程序環境可以讀取(解讀)和生成 JSON。html
JSON能夠做爲一個對象或者字符串存在,前者用於解讀 JSON 中的數據,後者用於經過網絡傳輸 JSON 數據。 JavaScript 提供一個全局的可訪問的 JSON 對象來對這兩種數據進行轉換。java
一個 JSON 對象能夠被儲存在它本身的文件中,這基本上就是一個文本文件,擴展名爲 .json, 還有 MIME type 用於 application/json.git
JSON從JS獲取靈感,天然能夠想象到它和JS對象結構上的類似,示例以下:github
{ "squadName" : "Super hero squad", "homeTown" : "Metro City", "formed" : 2016, "secretBase" : "Super tower", "active" : true, "members" : [ { "name" : "Molecule Man", "age" : 29, "secretIdentity" : "Dan Jukes", "powers" : [ "Radiation resistance", "Turning tiny", "Radiation blast" ] }, { "name" : "Madame Uppercut", "age" : 39, "secretIdentity" : "Jane Wilson", "powers" : [ "Million tonne punch", "Damage resistance", "Superhuman reflexes" ] }, { "name" : "Eternal Flame", "age" : 1000000, "secretIdentity" : "Unknown", "powers" : [ "Immortality", "Heat Immunity", "Inferno", "Teleportation", "Interdimensional travel" ] } ] }
能夠看出它由屬性名:屬性值組成,每一個數據用,隔開。json
JSON對象也能夠是一個數組:數組
[ { "name" : "Molecule Man", "age" : 29, "secretIdentity" : "Dan Jukes", "powers" : [ "Radiation resistance", "Turning tiny", "Radiation blast" ] }, { "name" : "Madame Uppercut", "age" : 39, "secretIdentity" : "Jane Wilson", "powers" : [ "Million tonne punch", "Damage resistance", "Superhuman reflexes" ] } ] //訪問方式示例 [0]["powers"][0]
JSON對象的訪問與JS對象訪問方式一致,由.和[]訪問。對於複雜的數據能夠採用鏈式訪問,示例以下:網絡
superHeroes["members"][1]["powers"][2]
訪問某網頁請求JSON數據,獲得後進行處理並顯示。app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JSON Test</title> <style> </style> </head> <body> <header> </header> <section> </section> </body> <script> var header = document.querySelector('header'); var section = document.querySelector('section'); var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; //建立一個HTTP請求對象 var request = new XMLHttpRequest(); //打開一個新的請求 參數:HTTP方法,URL request.open('GET', requestURL); //設置返回的數據格式,發送請求 request.responseType = 'json'; request.send(); //處理返回的數據,請求對象load事件只在請求成功時觸發 request.onload = function() { var superHeroes = request.response; populateHeader(superHeroes); //填充header showHeroes(superHeroes); //填充section } //定位header function populateHeader(jsonObj) { var myH1 = document.createElement('h1'); myH1.textContent = jsonObj['squadName']; header.appendChild(myH1); var myPara = document.createElement('p'); myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed']; header.appendChild(myPara); } //建立英雄信息卡片 function showHeroes(jsonObj) { var heroes = jsonObj['members']; for (i = 0; i < heroes.length; i++) { var myArticle = document.createElement('article'); var myH2 = document.createElement('h2'); var myPara1 = document.createElement('p'); var myPara2 = document.createElement('p'); var myPara3 = document.createElement('p'); var myList = document.createElement('ul'); myH2.textContent = heroes[i].name; myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity; myPara2.textContent = 'Age: ' + heroes[i].age; myPara3.textContent = 'Superpowers:'; var superPowers = heroes[i].powers; for (j = 0; j < superPowers.length; j++) { var listItem = document.createElement('li'); listItem.textContent = superPowers[j]; myList.appendChild(listItem); } myArticle.appendChild(myH2); myArticle.appendChild(myPara1); myArticle.appendChild(myPara2); myArticle.appendChild(myPara3); myArticle.appendChild(myList); section.appendChild(myArticle); } } </script> </html>
若是返回的數據並不是JSON對象,而是字符串,則處理以下:ide
request.open('GET', requestURL); request.responseType = 'text'; // now we're getting a string! request.send(); request.onload = function() { var superHeroesText = request.response; // get the string from the response var superHeroes = JSON.parse(superHeroesText); // convert it to an object populateHeader(superHeroes); showHeroes(superHeroes); }
反過來若是咱們想把json對象轉爲字符串,則處理以下:
var myJSON = { "name" : "Chris", "age" : "38" }; var myString = JSON.stringify(myJSON);