Sadie
Sadie

Reputation: 121

I keep getting Array to string conversion error using json_decode

I'm trying to convert a Json string in php pulled from my mySQL database. I've been successful with other strings like this using json_decode, but for some reason when I try decoding this string:

$Json ='{"S1": "15,2,0,4,0,0,1","S2": "50,0,99,1,5,1,1,0"}';

json_decode($Json, true);

I get the error 'Array to string conversion'.

I've been doing the same thing successfully with this string,

[{"group":"new","users":",12345678","S1":"56,3,0,0,0,6,0","S2":"0,0,49,0,4,0,0,0","enabled":"1","admin":"1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0"}]

I don't know what the differences between the two are, as they both are pulled from the same database, and both validate as Json successfully. Can someone tell me how I can successfully convert this so that I can get json_decode to work on it successfully? Thanks.

**update: Here's the actual code I'm using

$tmpUserJson = $row['JSONSettings’];    

$tmpUserJson='['.$tmpUserJson.']'; ///I’ve tried with and without brackets    

echo $tmpUserJson; //returns {"S1":"15,2,0,4,0,0,1","S2":"50,0,99,1,5,1,1,0”}    

$userJson = json_decode( $tmpUserJson , true);    

echo $userJson['S1']; // returns Notice: Array to string conversion    

Upvotes: 1

Views: 7470

Answers (2)

kourouma_coder
kourouma_coder

Reputation: 1098

$userJson = json_decode( $tmpUserJson , true);// this line return an associative array    

echo $userJson; // echo can't echo out an array that's why you got that error

As @David mentioned, if you want to echo out $userJson then you have couple of options:
1: loop through the array elements e.g : foreach($userJson as $value){ echo $value;}
2 for testing purpose : you can view $userJson data by using var_dump($userJson) or print_r($userJson); Good luck

Upvotes: 2

David Gilliam
David Gilliam

Reputation: 172

I think you get it because you are trying to echo out an array. Try:

$Json ='{"S1": "15,2,0,4,0,0,1","S2": "50,0,99,1,5,1,1,0"}';

$Json = json_decode($Json);

foreach( $Json as $item ){
    echo $item. "<br />";
}

Or you can var_dump your results: $Json ='{"S1": "15,2,0,4,0,0,1","S2": "50,0,99,1,5,1,1,0"}';

$Json = json_decode($Json);

var_dump($Json);

Upvotes: 2

Related Questions