Reputation: 213
Throughout HTML requests I download a JSON file from my database. This is the JSON file I get back.
{"_id":{"$oid":"5e8e09d0bf75d176ecfa2101"},"name":"Pasta al pomodoro","category":"Primi","ingredients":"","price":"15.99","available":true}{"_id":{"$oid":"5e8e0c2da73abb76ec812daf"},"name":"Cotoletta","category":"Carne","ingredients":"Cotoletta, Limone","price":"25.99","available":true}
I try converting the JSON file into a dictionary array so that I can select items by doing as an example:
myArray[0]['name']
This is the code I use to try and convert the JSON:
do {
let myArray = try (JSONSerialization.jsonObject(with: data, options : .mutableContainers) as? [Dictionary<String, Any>])!
print(myArray)
//completion(myArray, nil)
}
But it doesn't seem to work; it returns the error message:
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
Upvotes: 0
Views: 102
Reputation: 213
The problem was in the PHP server, as it did not issue the JSON file correctly. To fix it I had to make sure the PHP file echoed a "[" before the first DB row, include a "," between each DB row and end the file with a "]".
Before:
foreach ($rows as $document) {
echo(json_encode($document));
}
After:
echo "[";
foreach ($rows as $document) {
echo(json_encode($document));
echo (", ");
}
echo "]";
Upvotes: 0