0

I have the following string that corresponds to a JSON object.

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}'

And I would like to cast it to a stdClass. My current solution:

$object = (object)(array)json_decode($string);

While this is functioning, is there a better way? This seems messy and inefficient.

2
  • See: stackoverflow.com/a/931419/1531971 Commented Aug 24, 2018 at 15:54
  • This is not a valid string, because of the quoting, I'll assume that is just a typo $string = "{"status":..."; vs $string = '{"status": ...'; Commented Aug 24, 2018 at 15:56

2 Answers 2

2

This works, creating the associate array and passing true to json_decode:

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}';
$object = (object)json_decode($string, true);
var_dump($object);

object(stdClass)#1 (3) { ["status"]=> string(7) "success" ["count"]=> int(3) ["data"]=> array(1) { [0]=> array(1) { ["id"]=> int(112233) } } }

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

Comments

1

A much cleaner way would be:

$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}';

$object = json_decode($string);

check out what the output for print_r($object); looks like:

stdClass Object
(
    [status] => success
    [count] => 3
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 112233
                )

        )

Comments

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.