Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't decode JSON string in php

Tags:

json

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

like image 714
tech74 Avatar asked Aug 27 '10 16:08

tech74


People also ask

How to convert JSON in PHP?

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.

How to convert JSON array to string in PHP?

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.

What does JSON decode return?

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.


2 Answers

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.

like image 51
Peter Ajtai Avatar answered Oct 16 '22 15:10

Peter Ajtai


Try this:

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

$postarray = json_decode($json);
print_r($postarray);
like image 28
Andrei Serdeliuc ॐ Avatar answered Oct 16 '22 15:10

Andrei Serdeliuc ॐ