I have the following string:
{\"Coords\":[{\"Accuracy\":\"65\",\"Latitude\":\"53.277720488429026\",\"Longitude\":\"-9.012038778269686\",\"Timestamp\":\"Fri J
It was an old question, still answer to make it clear for someone who just encounters it like me.
try json_encode($traces);
in my case
return var_dump(json_encode($result[0]));
the result is:
string(34) "{"id":1,"content":"test database"}"
Try using this
$decoded_traces=json_decode($traces, true);
instead of this
$decoded_traces=json_decode($traces);
It will convert your stdClass to array. Note that $decoded_traces
is array then you can use as you require.
Instead of
$decoded_traces=json_decode($traces);
echo $decoded_traces;
try
$decoded_traces=json_decode($traces, true);
print_r $decoded_traces;
You get the error because you are trying to turn a stdClass object into a string, something it doesn't support.
Instead of echo $decoded_traces
try var_dump($decoded_traces)
- that will give a diagnostic view of the object you've decoded (which I presume is what you wanted). You should find it looks like this
class stdClass#1 (2) {
public $Coords =>
array(5) {
[0] =>
class stdClass#2 (4) {
public $Accuracy =>
string(2) "65"
public $Latitude =>
string(18) "53.277720488429026"
public $Longitude =>
string(18) "-9.012038778269686"
public $Timestamp =>
string(39) "Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"
}
[1] => (more of the same, edited for brevity)
[2] =>
[3] =>
[4] =>
}
public $Scan =>
string(8) "Whatever"
}
By default, json_encode will create stdClass objects like the above. If you would prefer an associative array, pass true
as the second parameter to json_decode
, e.g. $decoded_traces=json_decode($traces, true);
As a further aside, although stdClass can't be turned into a string, your own classes can - a class which implements the __toString magic method could be converted to a string!
use json_encode($traces)
this will convert the array into the string. json_decode()
is used to convert a string into array or object array
$decoded_traces
is an object. You cannot simply echo
an object, because that makes no sense.
If you want to debug the object, use var_dump($decoded_traces)
.