Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON decode - stdClass

Tags:

json

php

stdclass

I was having a question about making a 2D JSON string

Now I would like to know why I can't access the following:

$json_str = '{"urls":["http://example.com/001.jpg","http://example.com/003.jpg","http://example.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str);
// echo print_r($j_string_decoded); // OK

// test get url from second item
echo j_string_decoded['urls'][1];
// Fatal error: Cannot use object of type stdClass as array
like image 390
FFish Avatar asked Nov 02 '10 18:11

FFish


3 Answers

You are accessing it with array-like syntax:

echo j_string_decoded['urls'][1];

Whereas object is returned.

Convert it to array by specifying second argument to true:

$j_string_decoded = json_decode($json_str, true);

Making it:

$json_str = '{"urls":["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str, true);
echo j_string_decoded['urls'][1];

Or Try this:

$j_string_decoded->urls[1]

Notice the -> operator used for objects.

Quoting from Docs:

Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

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

like image 159
Sarfraz Avatar answered Oct 14 '22 22:10

Sarfraz


json_decode by default turns JSON dictionaries into PHP objects, so you would access your value as $j_string_decoded->urls[1]

Or you could pass an additional argument as json_decode($json_str,true) to have it return associative arrays, which would then be compatible with $j_string_decoded['urls'][1]

like image 34
Victor Nicollet Avatar answered Oct 14 '22 21:10

Victor Nicollet


Use:

json_decode($jsonstring, true);

to return an array.

like image 6
netcoder Avatar answered Oct 14 '22 21:10

netcoder