JSON (JavaScript Object Notation) 是一種輕量級資料交換格式,易於人閱讀、機器解析。它將 JavaScript 物件轉為字串,便於網路傳輸、儲存與跨語言交換。雖然源自 JavaScript,但已成為語言無關的標準格式。
{ "firstName": "Brett", "lastName": "McLaughlin", "email": "brett@example.com" }
{ "people": [
{ "firstName": "Brett", "lastName": "McLaughlin" },
{ "firstName": "Jason", "lastName": "Hunter" }
]}
{
"programmers": [ { "firstName": "Brett", "email": "brett@example.com" } ],
"authors": [ { "firstName": "Isaac", "genre": "science fiction" } ],
"musicians": [ { "firstName": "Eric", "instrument": "guitar" } ]
}
JSON 完全動態:同一結構中不同記錄可擁有不同欄位,無預定義 Schema 限制。
const people = {
"programmers": [ { "firstName": "Brett", "email": "brett@example.com" } ]
};
people.programmers[0].lastName; // "McLaughlin"
people.authors[1].genre; // "fantasy"
people.musicians[3].lastName; // undefined(索引超出)
people.musicians[1].lastName = "Rachmaninov";
const jsonString = JSON.stringify(people); // 標準方法
// 任何 JS 物件皆可轉換
const myObj = { x: 1, y: 2 };
const json = JSON.stringify(myObj);
注意: 現代瀏覽器使用 JSON.stringify() / JSON.parse(),舊文獻提到的 .toJSONString() 已過時。
PHP 5.2+ 內建支援,核心函數:
json_encode() - PHP 變數 → JSON 字串json_decode() - JSON 字串 → PHP 變數(物件/陣列)<?php
$arr = [
'name' => '深空',
'contact' => [
'email' => 'shenkong@qq.com',
'website' => 'https://www.jb51.net'
]
];
$json = json_encode($arr);
// {"name":"\u6df1\u7a7a","contact":{"email":"shenkong@qq.com","website":"https:\/\/www.jb51.net"}}
?>
重要: json_encode 需 UTF-8 編碼。若程式為 GB2312/Big5,中文需先 iconv() 或 mb_convert_encoding() 轉 UTF-8 再編碼,否則中文變 \uXXXX 或空值。
<?php
$obj = json_decode($json); // 回傳 stdClass 物件
$arr = json_decode($json, true); // 第二參數 true → 關聯陣列
echo $obj->name; // 深空
echo $arr['name']; // 深空
?>
<?php // api.php
header('Content-Type: application/json; charset=utf-8');
$data = ['status' => 'ok', 'user' => ['id' => 1, 'name' => 'Admin']];
echo json_encode($data);
?>
// 前端 JS
fetch('api.php')
.then(res => res.json())
.then(data => console.log(data.user.name)); // "Admin"
瀏覽器同源策略限制 AJAX 跨域,但 <script> 標籤不受限。JSONP 利用此特性:
<script>
function getProfile(data) {
document.getElementById('nick').innerText = data.nick;
}
</script>
<script src="https://api.example.com/profile.php"></script>
<?php // profile.php
$arr = ['nick' => '深空', 'email' => 'shenkong@qq.com'];
$json = json_encode($arr);
echo "getProfile($json)"; // 輸出:getProfile({"nick":"深空",...})
?>
瀏覽器載入 script 時,會執行 getProfile(...),實現跨域資料傳遞。現代專案建議改用 CORS 或代理方式,JSONP 僅支援 GET 且有安全風險。
const url = "process.php?data=" + encodeURIComponent(JSON.stringify(obj));
fetch(url);
注意 URL 長度限制與明文傳輸安全性。
fetch('process.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'data=' + encodeURIComponent(JSON.stringify(obj))
});
PHP 端接收:
<?php
$raw = file_get_contents('php://input'); // 取得原始 POST 資料
$data = json_decode($raw, true); // 解析為陣列
// 或表單欄位方式:
$data = json_decode($_POST['data'], true);
?>
| 問題 | 解決方案 |
|---|---|
| 中文編碼成 \uXXXX | 確保 PHP 檔案儲存為 UTF-8,資料庫連線設定 charset=utf8mb4 |
| json_decode 回傳 null | 檢查 JSON 格式是否合法(線上驗證工具),確認 UTF-8 無 BOM |
| 大數字精度遺失 | PHP 7.1+ 使用 json_decode($json, false, 512, JSON_BIGINT_AS_STRING) |
| 循環參考錯誤 | 物件實作 JsonSerializable 介面,自訂序列化邏輯 |
| 效能優化 | 大量資料考慮分頁、壓縮、或改用 MessagePack/Protocol Buffers |
JSON 以簡潔、通用、原生支援成為現代 Web API 事實標準。掌握 json_encode/decode、編碼處理、前後端交互模式(AJAX/JSONP/POST)、安全與效能考量,是 PHP 開發者必備核心技能。