JSON是一種資料交換格式。 資料型別: number boolean string null array[] object{ ... } JavaScript物件變成JSON,就是把這個物件序列化成一個JSON格式的字串 例如 var xiaoming = { name: '小明', age: 14, gender: true, height: 1.65, grade: null, 'middle-school': '"W3C" Middle School', skills: ['JavaScript', 'Java', 'Python', 'Lisp'] }; var s = JSON.stringify(xiaoming); console.log(s);
輸出{"name":"小明","age":14,"gender":true,"height":1.65,"grade":null,"middle-school":""W3C" Middle School","skills":["JavaScript","Java","Python","Lisp"]}
可以加上引數,按縮排輸出:JSON.stringify(xiaoming, null, ' '); 輸出{ "name": "小明", "age": 14, "gender": true, "height": 1.65, "grade": null, "middle-school": ""W3C" Middle School", "skills": [ "JavaScript", "Java", "Python", "Lisp" ] }
第二個引數用於控制如何篩選物件的鍵值,如果我們只想輸出指定的屬性,可以傳入Array: JSON.stringify(xiaoming, ['name', 'skills'], ' '); 輸出: { "name": "小明", "skills": [ "JavaScript", "Java", "Python", "Lisp" ] }
還可以傳入一個函式,
function convert(key, value) { if (typeof value === 'string') { return value.toUpperCase(); } return value; }
JSON.stringify(xiaoming, convert, ' ');
拿到一個JSON格式的字串,我們直接用JSON.parse()把它變成一個JavaScript物件
JSON.parse('{"name":"小明","age":14}'); // Object {name: '小明', age: 14}
用瀏覽器訪問Yahoo的天氣API,檢視返回的JSON資料,然後返回城市、氣溫預報等資訊
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json'; // 從遠端地址獲取JSON: $.getJSON(url, function (data) {
// 獲取結果:
var city = data.query.results.channel.location.city;
var forecast = data.query.results.channel.item.forecast;
var result = {
city: city,
forecast: forecast
};
alert(JSON.stringify(result, null, ' '));
複製程式碼
});