I spent a couple of hours looking at a few similar answers before posting my problems.
I am retrieving data from a table in my database and I want to encode it in JSON. However, the output of json_encode () is only valid if the table has one row. If more than one line exists, the test at http://jsonlint.com/ returns an error.
This is my request:
$result = mysql_query($query); $rows = array(); //retrieve and print every record while($r = mysql_fetch_assoc($result)){ $rows['data'] = $r; //echo result as json echo json_encode($rows); }
This gives me the following JSON:
{ "data": { "entry_id":"2", "entry_type":"Information Relevant to the Subject", "entry":"This is my second entry." } } { "data":{ "entry_id":"1", "entry_type":"My Opinion About What Happened", "entry":"This is my first entry." } }
When I run the test at http://jsonlint.com/ , it returns this error:
Parse error on line 29: ..."No comment" }}{ "data": { ---------------------^ Expecting 'EOF', '}', ',', ']'
However, if I use this first half of JSON ...
{ "data": { "entry_id":"2", "entry_type":"Information Relevant to the Subject", "entry":"This is my second entry." } }
... or if I check only the second half ...
{ "data":{ "entry_id":"1", "entry_type":"My Opinion About What Happened", "entry":"This is my first entry." } }
... the same test will return "Valid JSON".
I want to be able to output in one single [valid] JSON to each row of the table.
Any suggestion would be much appreciated.