开发者

Can't decode JSON string in php

I have the following JSON string, i try to decode with php json_decode but $postarray is always NULL, can't work out why this is?

Running on Debian 5.0 Linux php Client API version => 5.0.51a Json version 1.2开发者_StackOverflow社区.1

 $json = '{\"json\":[{\"username\":\"1062576\",\"accountId\":\"45656565\"}]}';

 $postarray = json_decode($json);
 print_r($postarray);

Thanks


The reason to escape double quotes (\") in a string, is if the string is double quoted.

Since you are escaping the double quotes, you should double (not single) quote your string, like this:

<?php
 $json = "{\"json\":[{\"username\":\"1062576\",\"accountId\":\"45656565\"}]}";

 $postarray = json_decode($json);
 print_r($postarray);
?>

Live Example

If you do want to single quote your string, then don't escape the double quotes, or use stripslashes() like Andrei suggested.

You can read about the four ways to specify a string in PHP, and the differences among them, here.


Try this:

<?php
$json = stripslashes('{\"json\":[{\"username\":\"1062576\",\"accountId\":\"45656565\"}]}');

$postarray = json_decode($json);
print_r($postarray);


You should enclose it in double quotes.


The string will not be parsed because it is enclosed in single quotes, so the backslashes are literal. If you remove them, use stripslashes, or enclose the string in double quotes, you should have no problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜