user3522457
user3522457

Reputation: 2963

jsonencode php doesn't return valid json?

I wrote this

if($stmt->execute()){
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         echo json_encode($obj) . ",";
    }
}

and it returned

{"tabId":1,"tabName":"Main","uId":"1"},{"tabId":2,"tabName":"Photography","uId":"1"},

how to remove the , to make it a valid json?

Upvotes: 0

Views: 60

Answers (1)

Quentin
Quentin

Reputation: 943100

Each time you go around the loop, you produce a valid JSON text (followed by a comma).

When you join them together (which is the effect of echoing out each time you go around) the result is invalid.

Put the values in an array. Only call json_encode at the end.

My PHP is pretty rusty, but I think this will do the job.

$data = Array();
if($stmt->execute()){
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         $data[] = $obj;
    }
}
echo json_encode($data);

Upvotes: 3

Related Questions