Organizational Research By

Surprising Reserch Topic

json decode to array

json decode to array  using -'php,json'

I am trying to decode a JSON string into an array but i get the following error.

  Fatal error: Cannot use object of type
  stdClass as array in
  C:\wamp\www\temp\asklaila.php on line

Here is the code:

$json_string = '';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);


asked Sep 15, 2015 by NanHunley
0 votes

Related Hot Questions

5 Answers

0 votes

As per the documentation, you need to specify if you want an associative array instead of an object from json_decode, this would be the code:

json_decode($jsondata, true);
answered Sep 15, 2015 by CarBrackman
0 votes

try this

$json_string = '';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "
answered Sep 15, 2015 by ToniaIvjcgtc
0 votes
answered Sep 15, 2015 by FrancescoCum
0 votes

This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);

... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

answered Sep 15, 2015 by RosieAdgtpba
0 votes
$userColumnRecords = '[{"col_name":"Name", "active":"true", "pos":1},{"col_name":"Address", "active":"true", "pos":2}]';
$userColData = json_decode($userColumnRecords, true);
answered Sep 15, 2015 by Brigida52Gg