二次json_encode() 和二次 json_decode()

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   ar   strong   sp   div   

之前沒有留意過這兩個函數,昨天群裡有人問起。發現如下事情。

header("Content-type:text/html;charset=utf-8");$arr = array(‘a‘=>1,‘b‘=>2);$str = json_encode($arr);var_dump($str);var_dump(json_encode($str));$str_1 = json_encode($str);var_dump($str_1);$arr_1 = json_decode($str_1);var_dump($arr_1);$obj = json_decode($arr_1);var_dump($obj);echo $obj->a;

結果:

string ‘{"a":1,"b":2}‘ (length=13)string ‘"{\"a\":1,\"b\":2}"‘ (length=19)string ‘"{\"a\":1,\"b\":2}"‘ (length=19)string ‘{"a":1,"b":2}‘ (length=13)object(stdClass)[1]  public ‘a‘ => int 1  public ‘b‘ => int 21

用json_encode() 二次或者N次 將會把之前轉好的json字串進行轉義。

來看下json_encode()的api

string json_encode ( mixed $value [, int $options = 0 ] )

這說第一個參數是混合類型的,除了resource 其餘都可以。 後面參數。不想偏離主題。

因為第一次調用json_encode()的時候傳的是數組,第二次調用json_encode()方法的時候參數是字串。

 

用json_decode();

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

 

api說只能放json字串。

但是我們進行第二次json_decode 的時候傳入的參數,其實是一個數組了。返回給我們了一個對象。

二次json_encode() 和二次 json_decode()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.