JSON是一種用純文字來描述資料結構,作為多種程式語言之間資料交換的格式,
JSON可以儲存(字串,數字,陣列,物件),
開始建立JSON
物件 (object):一個物件以「{」開始,並以「}」結束。
陣列:以「[」開始,並以「]」結束。
名稱/值:name / value 是成對的,中間透過 : 來區隔
以下是一個簡單的例子
{
"orderID": 12345,
"shopperName": "John Smith",
"shopperEmail": "johnsmith@example.com",
"contents": [
{
"productID": 34,
"productName": "SuperWidget",
"quantity": 1
},
{
"productID": 56,
"productName": "WonderWidget",
"quantity": 3
}
],
"orderCompleted": true
}
使用PHP來處理JSON資料,PHP提供兩個函式
json_encode():將資料轉成JSON格式
json_decode():處理json轉為變數資料以便程式處理
以下是將資料透過PHP轉JSON格式範例
<?php
$cart = array(
"orderID" => 12345,
"shopperName" => "John Smith",
"shopperEmail" => "johnsmith@example.com",
"contents" => array(
array(
"productID" => 34,
"productName" => "SuperWidget",
"quantity" => 1
),
array(
"productID" => 56,
"productName" => "WonderWidget",
"quantity" => 3
)
),
"orderCompleted" => true
);
echo json_encode( $cart );
?>
轉成JSON格式後,若要讓程式可以取得JSON變數資料,可以看以下這個範例
<?php
$jsonString = '
{
"orderID": 12345,
"shopperName": "John Smith",
"shopperEmail": "johnsmith@example.com",
"contents": [
{
"productID": 34,
"productName": "SuperWidget",
"quantity": 1
},
{
"productID": 56,
"productName": "WonderWidget",
"quantity": 3
}
],
"orderCompleted": true
}
';
$cart = json_decode( $jsonString );
echo $cart->shopperEmail . "<br />";
echo $cart->contents[1]->productName . "<br />";
?>
參考資料來源:
小惡魔 – 電腦技術 – 工作筆記 – AppleBOY
JSON Basics: What You Need to Know
----20150519補充---
線上測試json格式是否正確網站JSON Editor
當php中使用json_decode()將json格式轉換為物件使用,若想轉會為array使用則在json_decode($json,true),函式裡面第二的參數設置為true即可
