带有数字检查的 Laravel Response::json()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23996567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:35:30  来源:igfitidea点击:

Laravel Response::json() with numeric check

phpjsonlaravellaravel-4

提问by harryg

When performing an eloquent query on a model (using the MySQL driver) which has some numeric fields and then return a json response of the results, the json appears to pass numeric values as strings rather than numbers.

当对具有一些数字字段的模型(使用 MySQL 驱动程序)执行 eloquent 查询,然后返回结果的 json 响应时,json 似乎将数字值作为字符串而不是数字传递。

E.g.

例如

$properties = Model::find(6);
return Response::json($properties);

Returns something like:

返回类似:

{
    "name": "A nice item",
    "value": "160806.32"
}

When it should return:

什么时候应该返回:

{
    "name": "A nice item",
    "value": 160806.32
}

In normal php you can use the JSON_NUMERIC_CHECKto solve this but there appears to be no such option for the Response::json()method. How can I ensure numeric fields are returned as numbers rather than strings?

在普通的 php 中,您可以使用JSON_NUMERIC_CHECK来解决这个问题,但该Response::json()方法似乎没有这样的选项。如何确保数字字段作为数字而不是字符串返回?

回答by Kirill Fuchs

You can actually pass that option over. If we take a look at the source code for the JsonResponse classyou can pass json_encode options as the last parameter.

您实际上可以传递该选项。如果我们查看JsonResponse 类的源代码,您可以将 json_encode 选项作为最后一个参数传递。

It would look something like this

它看起来像这样

return Response::json($properties, 200, [], JSON_NUMERIC_CHECK);

Alternativelyyou could do this:

或者你可以这样做:

    return Response::make(
        $properties->toJson(JSON_NUMERIC_CHECK), 
        200, 
        ['Content-Type' => 'application/json']
    );

Note: if $propertiesis not an Elequoent model then it must at least implement the JsonableInterface

注意:如果$properties不是 Elequoent 模型,那么它至少必须实现JsonableInterface

as well as:

以及

    return Response::make(
        json_encode($properties->toArray(), JSON_NUMERIC_CHECK), 
        200, 
        ['Content-Type' => 'application/json']
    );

The toJson()method in Eloquent just wraps json_encode()and passes it the array of your model. I'd recommend using one of the first two options.

的toJSON()雄辩方法只是包装json_encode()并将其传递模型的数组。我建议使用前两个选项之一。

回答by Malta

Use method setEncodingOptionsof JsonResponse:

使用方法setEncodingOptionsJsonResponse

return response()->json($properties)->setEncodingOptions(JSON_NUMERIC_CHECK);