-->

Silex - app->json() returning integer data as stri

2019-05-11 07:11发布

问题:

I just started working with Silex to help me build a restful api that returns data from my MySQL database. Previously when working with php and mysql I noticed that MySQL would return integers as strings inside my json_encode() function. It would put quotes around all my integer values. The only way I was able to fix this was to pass JSON_NUMERIC_CHECK into the json_encode function:

return json_encode($array, JSON_NUMERIC_CHECK);

Worked lovely for what I needed. Now that I'm using silex I've been using it's built-in json function to return values from my controllers. I noticed I'm having the same problem with the integers getting returned as strings with quotes around them.

$app->get('/suppliers', function () use ($app) {
    $sql = "SELECT * FROM suppliers";
    $suppliers = $app['db']->fetchAll($sql);

    return $app->json(array('suppliers' => $suppliers));
});

Suppliers have a supplier_id field that is an integer, yet it is being returned as string in the json data. I tried passing JSON_NUMERIC_CHECK into the $app->json() function after my array but would get an InvalidArguementException.

I did figure out instead of using the $app->json() function I could just use json_encode() php function and it would work. Like so:

$app->get('/suppliers', function () use ($app) {
    $sql = "SELECT * FROM suppliers";
    $suppliers = $app['db']->fetchAll($sql);

    //return $app->json(array('suppliers' => $suppliers));
    return json_encode(array('suppliers' => $suppliers), JSON_NUMERIC_CHECK);
});

Is there any reason NOT to do it this way instead of using the silex $app->json() function? Is there a better way of doing this?

回答1:

$app->json(...) returns response JsonResponse. You can manually create this type of response and set encoding options.

$app->get('/suppliers', function () use ($app) {
    $sql = "SELECT * FROM suppliers";
    $suppliers = $app['db']->fetchAll($sql);

    $response = new \Symfony\Component\HttpFoundation\JsonResponse();
    $response->setEncodingOptions(JSON_NUMERIC_CHECK);
    $response->setData(array('suppliers' => $suppliers));

    return $response;
});

or set allready encoded content

$app->get('/suppliers', function () use ($app) {
    $sql = "SELECT * FROM suppliers";
    $suppliers = $app['db']->fetchAll($sql);

    $response = new \Symfony\Component\HttpFoundation\JsonResponse();
    $response->setContent(json_encode(array('suppliers' => $suppliers), JSON_NUMERIC_CHECK));

    return $response;
});


回答2:

try with setEncodingOptions

return $app->json($var, Response::HTTP_OK)->setEncodingOptions(JSON_NUMERIC_CHECK);