1

I am trying to loop through a JSON string using a foreach(). However I keep getting the following error:

"Notice: Trying to get property of non-object". 

The strange part is that when I copy and paste the JSON string and then run the foreach(), it work fine. Just to provide some detail, I am using the Best-Buy API.

Since this seemed to work fine for everyone here is it possible there is something wrong with the data that best buy is feeding me?

Please help, I have tried everything!

UPDATE sorry for not posting code. here it is:

$info = json_decode($test, true); 
function tagGen($info){
foreach($info as $key => $value){
 }  
Community
  • 1
  • 1
  • A code sample would be incredibly useful, as we have no idea whether you have a typo or a deeper issue. I'll take a stab at an answer anyways... – MikeMurko Dec 07 '11 at 06:21

3 Answers3

1

As you have not posted the code so we can just think that you have a string jason encoded. My dear json encoded string is some thing which is some sort of javascript form. And foreach is a php loop. So if you have a json encoded string and you want to use it in foreach loop you have to use json_decode function for that.

When you will apply json_decode you will be having a string From the documentation

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.

For some example code.

$str=json_decode($yourjson);
foreach($str as $key=>$value)
{}
zizozu
  • 501
  • 4
  • 9
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
  • It seems that as long as the Json is in a variable I get this error. When I put it through my foreach() as a string, after doing a print_r it works fine. – yuds schonfeld Dec 07 '11 at 06:45
0

You are probably not using json_decode on the JSON string. Take a look at how I would do this:

$json = "somejsonstring";
$json_array = json_decode($json, true);

foreach($json_array as $element) {
   echo $element['some key'];
}

Note the "true" second parameter given to the json_decode method. That returns an associative array rather than a standard PHP object. Makes it a lot easier to work with in foreach loops.

Hope that helps, although your question should really include a code sample.

MikeMurko
  • 2,214
  • 1
  • 27
  • 56
  • Thanks for the quick reply. I am using json_decode, here it is taken straight from the program. I am tearing my hair out. $test = curl_exec($curl_object); curl_close($curl_object); $info = json_decode($test, true); – yuds schonfeld Dec 07 '11 at 06:29
0

Print your json string somewhere you can copy it and then check if it is valid using this tool: http://jsonformatter.curiousconcept.com/

Razvan Pat
  • 21
  • 3