JSON 介紹及 JS 與 PHP 之間交換資料傳值

什麼是 JSON

JSON 是個以純文字為基底去儲存和傳送簡單結構資料,你可以透過特定的格式去儲存任何資料(字串,數字,陣列,物件),也可以透過物件或陣列來傳送較複雜的資料。一旦建立了您的 JSON 資料,就可以非常簡單的跟其他程式溝通或交換資料,因為 JSON 就只是純文字個格式。

JSON 的優點如下:

    相容性高
    格式容易瞭解,閱讀及修改方便
    支援許多資料格式 (number,string,booleans,nulls,array,associative array)
    許多程式都支援函式庫讀取或修改 JSON 資料

JSON 應用在哪些地方

JSON 最常用用在 Web 網頁程式從 Server 端傳送資料給 browser,典型範例就是透過 AJAX 方式交換 JSON 資料,底下簡單舉個範例

    使用者點選了線上產品縮圖
    JavaScript 透過 AJAX 方式將產品 ID 傳送給伺服器端
    伺服器端收到 ID,將產品資料 (ex 價格,描述) 編碼成 JSON 資料,並且回傳給瀏覽器
    JavaScript 收到 JSON 資料,將其解碼 (decode) 並且將資料顯示在網頁上

您也可以透過網頁將 JSON 資料傳到伺服器端,這都是可以的,把 POST 或 GET 資訊編碼成 JSON 格式即可,如果有在使用 jQuery,它提供了兩個函式處理 JSON,分別是 getJSON 跟 parseJSON。
如何建立 JSON 字串

可以透過底下規則來建立 JSON 字串

    JSON 字串可以包含陣列 Array 資料或者是物件 Object 資料
    陣列可以用 [ ] 來寫入資料
    物件可以用 { } 來寫入資料
    name / value 是成對的,中間透過 (:) 來區隔

物件或陣列的 value 值可以如下:

    數字 (整數或浮點數)
    字串 (請用 “” 括號)
    布林函數 (boolean) (true 或 false)
    陣列 (請用 [ ] )
    物件 (請用 { } )
    NULL

一個簡單的 JSON 範例

{
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
}

由上面例子我們可以發現 contents 陣列裡面又包含物件,透過上面例子,我們寫成 JavaScript 如下:
   
<script type="text/javascript">
var cart = {
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
};
</script>

如何利用 JavaScript 來處理 JSON 資料

直接看例子比較快:
   
<script type="text/javascript">

var cart = {
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
};

alert ( JSON.stringify( cart ) );

</script>

透過 JSON.stringify 來轉換資料,產生結果如下
   
{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com",
"contents":[{"productID":34,"productName":"SuperWidget","quantity":1},
{"productID":56,"productName":"WonderWidget","quantity":3}],
"orderCompleted":true}

如何將 JSON 字串傳入 JavaScript 變數
   
<script type="text/javascript">

var 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                   
}                                          
';

var cart = JSON.parse ( jsonString );

alert ( cart.shopperEmail );
alert ( cart.contents[1].productName );

</script>

結果如下

cart.shopperEmail 輸出 johnsmith@example.com cart.contents[1].productName 輸出 WonderWidget
利用 PHP 建立或讀取 JSON 資料

PHP 直接有寫好函式庫可以處理 JSON 字串,就是利用 json_encode 跟 json_decode

範例:
   
<?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 );
?>

輸出
   
{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com","contents":[{"productID":34,"productName":"SuperWidget","quantity":1},{"productID":56,"productName":"WonderWidget","quantity":3}],"orderCompleted":true}

大家可以發現,我們只要用 array 方式將資料輸出,再透過 json_encode 就可以了,接下來看看底下 PHP 如何讀取 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>";
?>

很簡單吧,PHP 利用了 json_decode 方式將 json 轉成變數資料以便讀取內容。
結論

這篇介紹主要是讓大家對 JSON 有基本得瞭解,以及如何用 JavaScript 跟 PHP 處理 JSON 資料,其實就不難,希望對大家有幫助。

留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令