Oreo Oreo - 3 months ago 29
JSON Question

PHP Encode column _id without double quotes

Encoding database data into JSON using following script:

if (mysql_num_rows($result) > 0) {

$response["detail"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$item = array();
$item["_id"] = $row["_id"];

array_push($response["detail"], $item);
}
// success
$response["success"] = 1;
}

// echoing JSON response
echo json_encode($response);


And getting response like this:

{"detail":[{"_id":"3"}],"success":1}


Whereas I was expecting this one:

{"detail":[{"_id":3}],"success":1}

Answer

The JSON_NUMERIC_CHECK flag introduced in 5.3.0.

echo json_encode( $response, JSON_NUMERIC_CHECK );

Please read this for more info http://php.net/manual/en/function.json-encode.php

Or

you may type cast the int id

 $item["_id"] = (int) $row["_id"];