Let me preface this question by saying I'm inexperienced with JSON, so please correct me if I say something wrong. I've searched for a few hours and can't find a solution to my question. So, I run some php which should return JSON containing 3 rows worth of data (top three users in a highscore table).
In the php file, I echo each row as such:
while ($row = $result->fetch_assoc()) {
echo (json_encode($row));
}
However, when I try to parse the output:
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do {
jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as! NSArray
} catch let error as NSError {
print(error)
}
}
The console throws the error:
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
Here is the actual output from the server:
{"userid":"8","name":"Sam","highscore":"215","rank":"1"}
{"userid":"9","name":"James","highscore":"210","rank":"2"}
{"userid":"10","name":"Julian","highscore":"162","rank":"3"}
This isn't valid according to jsonlint.com , but I don't know what I can do to solve the problem. Why isn't json_encode() placing commas after the }
brackets, and most importantly how do I fix the invalid JSON? Thank you.
You echo multiple JSON strings out, you need to combine your query result into 1 array, then turn it to a single JSON string:
$array = []
while ($row = $result->fetch_assoc()) {
$array[] = $row;
}
echo json_encode($array);
Your JSON will look something like this:
[
{"userid":"8","name":"Sam","highscore":"215","rank":"1"},
{"userid":"9","name":"James","highscore":"210","rank":"2"},
{"userid":"10","name":"Julian","highscore":"162","rank":"3"}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.