Looping through a JSON string - php

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){
}

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)
{}

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.

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

Related

Get Json Value with extra quotes using php

Get all value from json using json_decode. Given name is Juliet"es this json. If using json_decode this array will be change null value. how do i get this json to array
$jsonobj = '{"Name":"Juliet"es","Maths":37,"English":43}';
if anyone having any idea please post answer.
Try $convertedJson = json_decode(addslashes($jsonobj));.
But has suggested by #Barmar and #CBroe , always generated JSON strings from array or object with json_encode().

PHP: Getting associative array returns null, despite existing in var_dump

I have an array of 'servers' that I'm storing in a JSON file.
The JSON file looks like this:
{"1":{"available":1,"players":0,"maxplayers":4}}
I retrieve this value with this:
$servers = (array) json_decode(file_get_contents("activeservers.json"));
However, when I try to access the array with $server = $servers[$id], $server is null. I noticed that the key is in quotes, so I also tried casting $id to a string, and surrounding it with quotes (") which didn't work.
Something to note, is that this code is returning "NULL":
foreach(array_keys($servers) as $key){
var_dump($servers[$key]);
}
Your code is wrong. Also you don't need to type cast when doing a json_decode, you can instead set the second parameter to true more info here.
Also you don't need to use the array_keys function in your foreach loop,
try this.
$json = '{"1":{"available":1,"players":0,"maxplayers":4}}';
$servers = json_decode($json, true);
foreach($servers as $key => $value) {
print $value["available"];
}
Do a print_r($value) to get all the array keys available to use. Also you could take advantage of the $key variable to print out the array key of the parent array.
Thanks, #Rizier123 (who solved the question).
Apparently passing TRUE as the second parameter to my json_decode function fixes the issue.
After checking the PHP documentation for json_decode() (PHP: json_decode), it seems that passing this parameter means that the resulting decoded array is automatically converted into an associative array (and this is recurring, meaning that this automatically happens for sub-arrays).
Edit: #Rizier123 also says that "you might want to read: stackoverflow.com/a/10333200 to understand a bit better why it is so "weird" and your method didn't work properly."

How can i check if shape:[] is null in json with php

I have a json object like this :
{"Techne":{"#Version":"2.2","Author":"ZeuX","Name":"","PreviewImage":"","ProjectName":"","ProjectType":"","Description":"","DateCreated":"","Models":[{"Model":{"GlScale":"1,1,1","Name":"","TextureSize":"1,1","#texture":"texture.png","BaseClass":"ModelBase","Geometry":{"Folder":[],"Shape":[],"Piece":[],"Null":[]}}}]}}
How can I check if the array Shape:[] is empty with PHP I only know how to do it with JavaScript but this matter needs PHP to be used how can I do it?
You can use json_decode() and then access it's members.
$json = json_decode('{"Techne":{"#Version":"2.2","Author":"ZeuX","Name":"","PreviewImage":"","ProjectName":"","ProjectType":"","Description":"","DateCreated":"","Models":[{"Model":{"GlScale":"1,1,1","Name":"","TextureSize":"1,1","#texture":"texture.png","BaseClass":"ModelBase","Geometry":{"Folder":[],"Shape":[],"Piece":[],"Null":[]}}}]}}');
if(empty($json->Techne->Models[0]->Model->Geometry->Shape))
echo "Shape is empty";
json_decode() will give you an object in this case, because that is how this JSON string is formatted. You can learn more by searching about JSON and PHP, there are plenty of tutorials that will help you understand better.
I hope it helped you.

parsing text / json with php

{"email":"test#example.com","timestamp":1346345321,"newsletter":{"newsletter_user_list_id":"3648511","newsletter_id":"613267","newsletter_send_id":"657025"},"category":["EST_TEST","Newsletter"],"event":"open"}
I'm having trouble parsing this string. It's from Sendgrid's Event API, it seems to be "almost" JSON, but json_decode won't work. My goal is to get the data into an array, then into a MySQL table. I'm not asking anyone to write the code for me, just point me toward the correct method. Do I use the explode function, then json_decode?.
(I'm slowly teaching myself PHP, sorry if the question is not clear)
I think you're not using the json_decode function with $assoc = true, so you're getting an object rather than an array
$json =
'{"email":"test#example.com","timestamp":1346345321,"newsletter":{"newsletter_user_list_id":"3648511","newsletter_id":"613267","newsletter_send_id":"657025"},"category":["EST_TEST","Newsletter"],"event":"open"}';
var_dump(json_decode($json, true));
You'll get the result as array;

json decode and encode - iterate through multi dimensional array and remove key value if equals certain value

Basically the json output is this -output is from php.
[{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"},{"attr":{"id":"node_3","rel":"drive"},"data":"D:","state":"closed"}]
so because rel is equal to default
{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"}
I need to remove this from the array.
I have thought of maybe using
foreach($arr as $key => &$item) {
if ($value['rel'] == 'default'{
unset($arr[$key]);
This however, wont work for some reason. I have no idea if my method is the best way, or whether there is a better way to achieve this.
I also need to decode and encode it.
You can use json_encode and json_decode to parse the json as Jesse Bunch said.
After i decoded the json you posted, it returned as an object. To call on an object you have to do things a bit diffrent.
$arr = json_decode('[{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"},{"attr":{"id":"node_3","rel":"drive"},"data":"D:","state":"closed"}]');
foreach($arr as $key => $row)
{
if ($row->attr->rel == 'default'){
unset($arr[$key]);
}
}
var_dump($arr);
The $arr does no longer contain the default rel
In most languages, mutating an array while you're looping it is frowned upon. In PHP, there is nothing that say you cannot mutate an array while looping it. What you're doing is absolutely fine and probably the most efficient way of doing it.
As for encoding and decoding, see json_encode and json_decode.

Categories