還不知道 JSON 是什麼嘛?本篇教學會帶您瞭解 JSON 在網站上的應用,以及運作流程跟使用 PHP 和 JavaScript 來處理 JSON。假如您現在的工作就是網站設計師,相信一定聽過 JSON,但是什麼是 JSON,它能夠做什麼,及您能透過它在網站上做到哪些事情呢?
透過本篇介紹您可以瞭解基本的 JSON,底下會列出本篇會提到的重點:
- 什麼是 JSON
- JSON 應用在哪些地方
- 如何建立 JSON 字串
- 一個簡單的 JSON 範例
- JSON vs XML
- 如何透過 PHP 及 JavaScript 使用 JSON
什麼是 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 範例
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 | {
  "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 如下:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 | 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
};
 | 
JSON vs XML
在許多方面,你可以想像 JSON 來替代 XML,在過去 Web Application 開發 AJAX 都是透過 XML 來交換資料,但是你可以發現近幾年來 JSON 已經漸漸取代 XML 格式了,為什麼會變成這樣呢?因為 JSON 格式容易閱讀且好修改,許多程式語言分別開發了函式庫來處理 JSON 資料,我們可以把上面的 JSON 資料改寫成 XML 如下:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 | <object>
  <property>
    <key>orderID</key>
    <number>12345</number>
  </property>
  <property>
    <key>shopperName</key>
    <string>John Smith</string>
  </property>
  <property>
    <key>shopperEmail</key>
    <string>johnsmith@example.com</string>
  </property>
  <property>
    <key>contents</key>
    <array>
      <object>
        <property>
          <key>productID</key>
          <number>34</number>
        </property>
        <property>
          <key>productName</key>
          <string>SuperWidget</string>
        </property>
        <property>
          <key>quantity</key>
          <number>1</number>
        </property>
      </object>
      <object>
        <property>
          <key>productID</key>
          <number>56</number>
        </property>
        <property>
          <key>productName</key>
          <string>WonderWidget</string>
        </property>
        <property>
          <key>quantity</key>
          <number>3</number>
        </property>
      </object>
    </array>
  </property>
  <property>
    <key>orderCompleted</key>
    <boolean>true</boolean>
  </property>
</object>
 | 
大家有沒有發現 XML 的資料量遠大於 JSON 資料量,這也是 JSON 優於 XML 的原因之一
如何利用 JavaScript 來處理 JSON 資料
直接看例子比較快:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 | 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 ) ); 
 | 
透過 JSON.stringify 來轉換資料,產生結果如下
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 | {
   "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 變數
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 | 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 );
 | 
結果如下
| 1
2
 | cart.shopperEmail 輸出 johnsmith@example.com 
cart.contents[1].productName 輸出 WonderWidget
 | 
利用 PHP 建立或讀取 JSON 資料
PHP 直接有寫好函式庫可以處理 JSON 字串,就是利用 json_encode 跟 json_decode
範例:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 | $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 );
 | 
輸出
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 | {
   "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 字串
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 | $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 資料,其實就不難,希望對大家有幫助。
本篇範例皆來自 JSON Basics: What You Need to Know 文章
See also