0
votes

I'm trying to decode the following JSON using php json_decode function.

[{"total_count":17}]

I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:

https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22

3
It's an array with a single object, with one key/value pair.Mike Christensen
The above string is valid for json, i dun understand why you can't do the decode. You might need to include your code for decodeajreal
What is your error/output? It decodes correctly for me.lethal-guitar
Is the problem decoding it or using it? Did you keep in mind that the result is an array?OnaBai
I forgot that the result was an array. ThanksSyed Balkhi

3 Answers

2
votes

PHP's json_decode returns an instance of stdClass by default.

For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:

$var = json_decode('[{"total_count":17}]', true);

After that, you can access the variable as $result[0]['total_count']

0
votes

See this JS fiddle for an example of how to read it:

http://jsfiddle.net/8V4qP/1

It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:

<?php
    $result = json_decode('[{"total_count":17}]', true);
    print $result[0]['total_count'];
?>

if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.

0
votes
$json = "[{\"total_count\":17}]";

$arr = Jason_decode($json);
foreach ($arr as $obj) {
    echo $obj->total_count . "<br>";
}

Or use json_decode($json, true) if you want associative arrays instead of objects.