0

I have a JSON response that looks like this:

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

I am trying to turn it into a PHP object like this:

$obj = json_decode($data,true);

But $obj is alway null. Can anyone tell me what I am doing wrong?

EDIT

This is my ajax request.

response = JSON.stringify(response);

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

1 Answer 1

2
  • You have to decode the HTML first
  • You have to not specify true as the second argument (that means "create an associative array instead of an object)

Such:

<?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);
?>

Outputs:

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
        )

)
Sign up to request clarification or add additional context in comments.

8 Comments

The response literally has &quot;?
@user3167249 — JSON uses " to delimit strings. You can't use the HTML &quot;.
Why not html_entity_decode()? Is there a specific reason as to why you chose htmlspecialchars_decode?
is that because I am sending it through post? This is the variable value before I submit it to php: {"order_product_id":"6","design_order":["design_number_1"],"design_number_1":{"sort_order":["Design Number"],"Design Number":"1"}}
@user3167249 — If that is what you are sending, then you shouldn't get the data in the format you claim you do in the question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.