JSON 基本結構
var user = {
"username": "andy",
"age": 20,
"info": { "tel": "123456", "cellphone": "98765" },
"address": [
{ "city": "beijing", "postcode": "222333" },
{ "city": "newyork", "postcode": "555666" }
]
};
console.log(user.username); // andy
console.log(user.address[0].city); // beijing
修改資料
user.username = "Tom";
console.log(user.username); // Tom
序列化為 JSON 字串
- 現代瀏覽器:
JSON.stringify(user)
- 舊專案引用
json2.js 或 prototype.js 提供的 .toJSONString()。
解析 JSON 字串
- 現代:
JSON.parse(str)
- 舊:
eval('(' + str + ')')(有安全風險)或 str.parseJSON() (Prototype)。
AJAX 串接範例
// 前端發送 JSON
var car = { make: 'Dodge', model: 'Coronet R/T', year: 1968, color: 'yellow' };
$.ajax({
url: '/MyWebApp/JSONTest1',
type: 'GET',
data: { car: JSON.stringify(car) },
success: function(resp) {
var obj = JSON.parse(resp);
console.log(obj.name, obj.age);
}
});
// 後端 (Java Servlet) 使用 org.json
JSONObject jsonObj = new JSONObject(request.getParameter("car"));
String model = jsonObj.getString("model");
int year = jsonObj.getInt("year");
// 回傳 JSON
JSONObject result = new JSONObject();
result.put("name", "Violet").put("occupation", "developer").put("age", 22);
response.getWriter().print(result.toString());
安全性提醒
- **嚴禁使用 eval 解析不可信來源 JSON**,必須用
JSON.parse。
- 傳輸敏感資料請使用 HTTPS。
- 後端輸出 JSON 時設定
Content-Type: application/json; charset=utf-8。
常見陷阱
- 日期物件序列化為 ISO 字串,反序列化需手動
new Date(str)。
- 循環參考會導致
JSON.stringify 拋錯,需自訂 replacer 或使用 flatted 套件。