Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_decode returns string type instead of object

Tags:

json

php

I'm passing a JSON-encoded string to json_decode() and am expecting its output to be an object type, but am getting a string type instead. How can I return an object?

In the docs, the following returns an object:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));

However, if I json_encode() the string first and then call json_decode(), the output is a string and not an object:

$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));

This is just a simplified example. In practice what I'm doing is pushing a JSON-encoded string to PHP via AJAX. However it does illustrate the problem of converting this encoded JSON string to an object I can read in PHP, e.g., "$json->a".

How can I return an object type?

thanks for the replies ! The actual context for this question was am using a JSON Response from a API. But when I do the json_decode to this response and try to access the values like - $json=json_decode(json response from API); echo $json->a it gives me a error: Object of class stdClass could not be converted to string

like image 665
Shakul Saini Avatar asked Aug 31 '12 06:08

Shakul Saini


1 Answers

The function json_encode is used to encode a native PHP object or array in JSON format.

For example, $json = json_encode($arr) where $arr is

$arr = array(
  'a' => 1,
  'b' => 2,
  'c' => 3,
  'd' => 4,
  'e' => 5,
);

would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'. At this point, you do not need to encode it again with json_encode!

To obtain your array back, simply do json_decode($json, true).

If you omit the true from the call to json_decode you'll obtain an instance of stdClass instead, with the various properties specified in the JSON string.

For more references, see:

http://www.php.net/manual/en/function.json-encode.php

http://www.php.net/manual/en/function.json-decode.php

like image 112
Matteo Tassinari Avatar answered Oct 26 '22 00:10

Matteo Tassinari