Json_decode returns string type instead of object

I pass the JSON encoded string to json_decode() and expect its output to be an object type, but instead I get a string type. How can I return an object?

In documents, 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() string first, and then call json_decode() , the output will be a string, 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 in PHP through AJAX. However, it illustrates the problem of converting this encoded JSON string to an object that I can read in PHP, for example, " $json->a ".

How to return an object type?

thanks for answers! The actual context for this question, I used the JSON Response from the API. But when I do json_decode for this answer and try to access values ​​like - $ json = json_decode (json response from the API); echo $ json-> a this gives me an error: an object of class stdClass cannot be converted to a string

+6
source share
3 answers

The json_encode function is used to encode your own 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, ); 

will 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 get the array back, just do json_decode($json, true) .

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

For more information, see the following sections:

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

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

+4
source
 var_dump(json_decode($json, true)); 

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

0
source

Instead of writing to a JSON array, try putting it into a PHP array first.

 <?php $array = array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 ); //Then json_encode() $json = json_encode($array); echo $json; die; ?> 

In this case, you are using ajax. Therefore, when you get success, you can do this:

 $.ajax({ url: 'example.com', data: { }, success: function(data) { console.log(data); } }); 

Where after the data inside console.log () can add json var as data.a, data.b ...

Also, with the string you provided, you do not need json_encode, since it is alrady in json format

0
source

Source: https://habr.com/ru/post/924245/


All Articles