PHP操作json

來源:互聯網
上載者:User
json只接受utf-8編碼的字元,所以php的函數json_encode()的參數必須是utf-8編碼

json格式:

============================

錯誤的json格式:

$error_json = "{ 'name': 'jack' }"; //json的分隔字元只允許使用雙引號,不能使用單引號
$error_json = '{ name: "jack" }'; //json鍵值對的"鍵"(冒號左邊的部分),必須使用雙引號
$error_json = '{ "name": "baz", }'; //最後一個值之後不能添加逗號

=============================

正確的json格式

$yes_json= '{"name":"jack"}';

PHP下的操作:

(1).json_encode()函數:將數組和對象,轉換為json格式

例如:

①將鍵/值對數組轉為json格式,將變成對象形式的json

  $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
  echo "json化後arr為:".json_encode($arr);
  ==================================================
  json化後arr為:{"a":1,"b":2,"c":3,"d":4,"e":5}

②將索引數組轉為json格式,將變成數組形式的json 

  $arr = Array('one', 'two', 'three');
  echo json_encode($arr);
  ==================================================
  ["one","two","three"]

將索引數組強制轉化成對象:

  json_encode( (object)$arr );
  或者
  json_encode ( $arr, JSON_FORCE_OBJECT );

③將類的對象轉為json格式,只保留public的欄位

class ClassA {  
    const ERROR_CODE = '404';  
    public $public_var = 'this is public_var';  
    private $private_var = 'this is private_var';
    protected $protected_var = 'this is protected_var';   
    public function getErrorCode() {  
      return self::ERROR_CODE;  
    }  
 }

========================================

$ClassA = new ClassA;  
$classA_json = json_encode($ClassA);  
echo $classA_json;
========================================
{"public_var":"this is public_var"}

(2).json_decode()函數,將json格式的字串轉化為php變數,預設轉為object對象,當傳入第二個參數為true時,轉為php數組

例如:

①.轉為php對象  

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}
var_dump($json);
=============================================
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

②.轉為php數組

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
=============================================
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

以上就介紹了PHP操作json,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.