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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 17:58:50

问题


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);


来源:https://stackoverflow.com/questions/35142601/silex-app-json-returning-integer-data-as-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!