JSON Encode not giving out right json string
I am trying to echo a json string in PHP which retrieves data from mySql database Bt when i validate json string in JSONlint it gives error:
Parse error on line 4:
...placesname": "abc"}{ "0": "abc",
----------------------^
Expecting 'EOF', '}', ',', ']'
开发者_运维知识库And my PHP code is:
$query = mysql_query("SELECT placesname FROM Places;");
while ($row = mysql_fetch_array($query)){
echo json_encode($row);
}
You're appending all your rows together into one string. You need to make an array of your rows, and then json_encode
the array.
You're creating JSON like this:
{"key": "value", "key2": "value2"}{"key": "value", "key2": "value2"}{"key": "value", "key2": "value2"}
Which isn't valid JSON. It needs to look like this:
[
{"key": "value", "key2": "value2"},
{"key": "value", "key2": "value2"},
{"key": "value", "key2": "value2"}
]
which is what you'll get if you json_encode
an array of objects.
I'm not a PHP expert, but try something along these lines:
$query = mysql_query("SELECT placesname FROM Places;");
$rows = Array();
while ($row = mysql_fetch_array($query)){
$rows[] = $row;
}
echo json_encode($rows);
Try this..
$query = mysql_query("SELECT placesname FROM Places;");
$data = array();
while ($row = mysql_fetch_array($query)){
$data[]=$row['placesname'];
}
echo json_encode($data);
精彩评论