php中怎麼講json字串轉json對象
代言
代言 2017-06-30 09:56:25
0
2
889


類似js中

msg = eval('(' msg ')');

的寫法

目前知道php對字串json 使用json_decode() 傳回都是null,百度不到其他方法

代言
代言

全部回覆(2)
曾经蜡笔没有小新
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

結果分別是

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

如果你json_decode後回傳null,你是不是把字串寫成這樣了"{ 'bar': 'baz' }",這個在JS裡是可以正常解析成JSON的,但是PHP裡面要寫成' { "bar": "baz" }',屬性和值要用雙引號

世界只因有你

用json_decode(),前提是json格式屬性和值要用雙引號,用python的話可以​​不用雙引號

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!