Luke Luke - 1 month ago 18
JSON Question

PHP and JSON - extra comma in results

I'm trying to return json response in the correct format but I am getting an extra 'comma' in the returned code (comma after the last item 'Pencil'):

{
"results": [{
"ItemID": 1,
"ItemName": "Ball"
}, {
"ItemID": 2,
"ItemName": "Pen"
}, {
"ItemID": 3,
"ItemName": "Pencil"
},
}]
}


I tried different things but I can't get rid of it. Would anybody have any idea how to remove it?

The code that i have is this:

<?php

print '{"results":[';
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();

$JSONArray = array(
"ItemID" => $ItemID,
"ItemName" => $ItemName
);
print ",";

print json_encode($JSONArray);


}

print "]}"

?>

Answer

You're doing it ENTIRELY wrong. You're outputting multiple independent JSON strings, which is outright wrong. JSON is a monolithic "structure", and building it piece-wise is highly risky.

Simple: DOn't do that.

You build a standard PHP array, then do ONE SINGLE encoding when you're completely done building:

$arr = array();

for(...) {
    $arr[] = ... add stuff ..
}

echo json_encode($arr);