0

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);
}
Jim
  • 22,354
  • 6
  • 52
  • 80
IphoneBites
  • 157
  • 1
  • 7
  • 17

2 Answers2

3

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);
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • @IphoneBites: E.g., there's no comma because you're not outputting a comma between rows, `json_encode` can only encode what you give it. You'll want to output a `[` before your loop and `,` after each row, then a `]` after your loop. (You may want to suppress the trailing comma after the last row. It's valid in JSON, but that doesn't mean all JSON parsers get it right, particularly not those relying on `eval` and running on IE.) – T.J. Crowder Aug 16 '11 at 10:10
  • @T.J. Crowder - actually, a trailing comma *isn't* valid JSON: http://stackoverflow.com/questions/201782/can-you-use-a-trailing-comma-in-a-json-object/201784#201784 (it *is* valid JavaScript though!) – Skilldrick Aug 16 '11 at 10:17
  • `@Skilldrick:` I'm truly shocked by that, but having looked through the grammar in [Section 15.12.1](http://es5.github.com/#x15.12.1), which is much more thorough that the vague overview given on [json.org](http://json.org), I'm forced to agree -- it's *not* valid JSON. It should be, but apparently it isn't. *sigh* – T.J. Crowder Aug 16 '11 at 11:01
  • @T.J. Crowder - Yeah, it *should* be :) Though I understand why it's not - makes parsers simpler, and IE will work when it's `eval`ed. Tbf, the railroad diagrams on json.org do imply this, but it's not stated explicitly. – Skilldrick Aug 16 '11 at 11:54
0

Try this..

$query  = mysql_query("SELECT placesname FROM Places;");
$data = array();
while ($row = mysql_fetch_array($query)){
    $data[]=$row['placesname'];
}

echo json_encode($data);
mysterious
  • 1,450
  • 5
  • 29
  • 56