1

I have a JSON object like below, which is stored in a variable called $product.

{"id":30} 

When I try to access the stored value though, I get the following error:

Trying to get property of non-object

Here is what I am doing:

echo $product->id; 

Alright folks, sorry for the wild goose chase. Apparently $products was an array and not a JSON data, which is really odd because print_r($products) and echo $products gave different results.

The results can be viewed here:

results

I am using Laravel, and usually laravel returns a nice JSON object from an SQL query, I must have changed something somewhere, which is why this happened. Thanks.

1
  • Do you test json_decode() after calling json_encode() -- $obj = json_decode(json_encode($product)); echo $obj->id; Commented Sep 30, 2014 at 8:45

4 Answers 4

1

Try following json_decode function

$product = '{"id":30}'; $t = json_decode($product); echo $t->id;exit; 
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work, gives me an error "Object of class stdClass could not be converted to string"
If I try json_decode($product, true); then I get the following error "Array to string conversion"
0

You could use json_decode to your object.

Takes a JSON encoded string and converts it into a PHP variable.

usage:

print_r(json_decode($obj, true)); var_dump(json_decode($obj)); 

8 Comments

@sarovarc try this print_r(json_decode($product, true));
Give the following error Array to string conversion
@sarovarc try print_r($product);
Ok there's definitely something odd going on:
@sarovarc that is what I thought glad it helped ;)
|
0

Trying below sample :

<?php $product = '{"id": 30}'; $obj = json_decode(json_encode($product)); // or json_decode(json_encode($product), true); echo $obj->{'id'}; // or echo $obj->id ?> 

Comments

0

The first examples are working for me, make sure you PHP is supporting the json_decode() function. Or you could try this:

$product = '{"id":30}'; $t = json_decode($product, true); echo $t["id"]; 

Passing the true value converts it to an array instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.