user5443928
user5443928

Reputation:

Could not convert json string to array using PHP

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.

$education=$_POST['education'];

the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null

$edu=json_decode($education,true);
print_r($edu);

It gives the empty output. Here I need to convert it to array and populate all data. Please help me.

Upvotes: 0

Views: 1391

Answers (2)

Bhaskar Jain
Bhaskar Jain

Reputation: 1691

In php, you can use this function to check valid json:

function _isJsonString($string) {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

You can also check online for valid json: http://json.parser.online.fr/ Hope this will help.

Upvotes: 0

ismael ansari
ismael ansari

Reputation: 486

Hi You need to make your json string like below:

$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;

it will show your output like below:

Array
(
[0] => stdClass Object
    (
        [name] => aaa
        [id] => 12
    )

[1] => stdClass Object
    (
        [name] => bbb
        [id] => 20
    )

)

Upvotes: 1

Related Questions