0

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.

  • 2
    Use double quote for json and try [{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}] – Saji May 09 '17 at 05:59
  • 3
    The JSON string has the wrong quotes. [See here](http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response), only double quotes are allowed. – Imanuel May 09 '17 at 06:00
  • Not a valid JSON click [here](https://jsonlint.com/?json=[{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]) @user6838959 JSON is passed valid test [here](https://jsonlint.com/?json=[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]) – Aravindh Gopi May 09 '17 at 06:22

2 Answers2

1

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
    )

)
ismael ansari
  • 486
  • 2
  • 8
0

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.

Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20