简体   繁体   中英

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.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);

你应该用双引号括起来。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM