JSON หรือ JavaScript Object Notation ซึ่งเป็นรูปแบบของการแลกเปลี่ยนข้อมูลแบบนึง (data-interchange format) ที่คล้าย ๆ กับ XML (มี concept คล้าย ๆ กันคือ "humans to read and write" (หรือเปล่า)) เพียงแต่ว่าใช้โครงสร้างข้อมูลของ Object ของ JavaScript มาใช้แทน ด้วยเหตุผลว่าไม่ต้องมานั่งแปลงข้อมูลไปมาระหว่าง XML กับ Data type object ใน JavaScript ถ้าสื่อสารกันระหว่าง JavaScipt กันตรง ๆ ก็โยนใส่ JSON ไปเลยไม่ต้องเสียเวลา convert จริง ๆ ผมว่ามันคล้ายกับ CSV มากกว่าอีกนะ -_-‘ แต่ว่าตัวนี้มันดีกว่าตรงที่มันถูกจับคู่ระหว่าง field กับ value เป็นคู่ ๆ ทำให้จะสลับตำแหน่งยังไงขอให้มันอยู่เป็นคู่กันเป็นใช้ได้
ถ้าคิดง่าย ๆ ก็คือ Array ทุก element จะมี index และ value หรือใน Associative Array ที่มี associative key และ value แล้วก็เอามาแปลงเป็น JSON ก็ไม่ยากอะไร จริง ๆ ตัว code นี้ผมไม่ได้คิดเอง ผมนำมาจาก array2json() – Convert PHP arrays to JSON น่าจะช่วยในการแปลง array ของ PHP มาเป็น JSON ได้ง่ายขึ้น
หลายคนคงถามว่าทำไมไม่เขียนเอง ไม่ยากหรอก ก็ตอบไปเลยว่า ของมันมีอยู่แล้ว เขียนเองทำไม ? ถ้ามันไม่ดี ค่อยมาปรับทีหลังน่าจะง่ายกว่า และเสียเวลาน้อยกว่าครับ ;)
- < ?php
- function array2json($arr) {
- $parts = array();
- $is_list = false;
- //Find out if the given array is a numerical array
- $keys = array_keys($arr);
- $max_length = count($arr)-1;
- if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
- $is_list = true;
- for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
- if($i != $keys[$i]) { //A key fails at position check.
- $is_list = false; //It is an associative array.
- break;
- }
- }
- }
- foreach($arr as $key=>$value) {
- if(is_array($value)) { //Custom handling for arrays
- if($is_list) $parts[] = array2json($value); /* :RECURSION: */
- else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
- } else {
- $str = '';
- if(!$is_list) $str = '"' . $key . '":';
- //Custom handling for multiple data types
- if(is_numeric($value)) $str .= $value; //Numbers
- elseif($value === false) $str .= 'false'; //The booleans
- elseif($value === true) $str .= 'true';
- else $str .= '"' . addslashes($value) . '"'; //All other things
- // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
- $parts[] = $str;
- }
- }
- $json = implode(',',$parts);
- if($is_list) return '[' . $json . ']';//Return numerical JSON
- return '{' . $json . '}';//Return associative JSON
- }
- ?>
ลองทดสอบด้วย
- $data = array('firstname'=>'Ford', 'lastname'=>'AntiTrust');
- echo array2json($data);
ผลก็คือ
- {"firstname":"Ford","lastname":"AntiTrust"}
หวังว่าคงเป็นประโยชน์กับใครหลาย ๆ คนนะครับ ;)
[Update – 8/11/2007 10:00] ตัว code มีปัญหานิดหน่อย -_-‘ แก้แล้วครับ