Json_Decode没有解码成对象

时间:2014-03-04 17:21:29

标签: php jquery ajax json

我有一个JSON响应,如下所示:

{"order_product_id":"6","design_order":["design_number_1"],"design_number_1":{"sort_order":["Design Number"],"Design Number":"1"}}

我试图把它变成像这样的PHP对象:

$obj = json_decode($data,true);

但是$ obj总是空的。谁能告诉我我做错了什么?

修改

这是我的ajax请求。

response = JSON.stringify(response);

        $.ajax({
            type: "POST",           
            url: "<?php echo $submit_url; ?>",
            data: { 'data' :response},
            success: function(data){
                alert(data);
                console.log(data);  
            }
        })

1 个答案:

答案 0 :(得分:3)

  • 您必须首先解码HTML
  • 你必须指定true作为第二个参数(这意味着“创建一个关联数组而不是一个对象)

这样:

<?php
$data = "{&quot;order_product_id&quot;:&quot;6&quot;,&quot;design_order&quot;:[&quot;design_number_1&quot;],&quot;design_number_1&quot;:{&quot;sort_order&quot;:[&quot;Design Number&quot;],&quot;Design Number&quot;:&quot;1&quot;}}";
$data = htmlspecialchars_decode($data);
$obj = json_decode($data);
print_r($obj);
?>

输出:

stdClass Object
(
    [order_product_id] => 6
    [design_order] => Array
        (
            [0] => design_number_1
        )

    [design_number_1] => stdClass Object
        (
            [sort_order] => Array
                (
                    [0] => Design Number
                )

            [Design Number] => 1
        )

)