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
Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.
Using json_encode() function to convert an Array to a string To convert an array to a string, one of the common ways to do that is to use the json_encode() function which is used to returns the JSON representation of a value.
The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With