har*_*ryg 6 php json laravel laravel-4
当对具有一些数字字段的模型(使用MySQL驱动程序)执行雄辩查询然后返回结果的json响应时,json似乎将数值作为字符串而不是数字传递.
例如
$properties = Model::find(6);
return Response::json($properties);
Run Code Online (Sandbox Code Playgroud)
返回类似于:
{
"name": "A nice item",
"value": "160806.32"
}
Run Code Online (Sandbox Code Playgroud)
什么时候应该返回:
{
"name": "A nice item",
"value": 160806.32
}
Run Code Online (Sandbox Code Playgroud)
在普通的PHP中你可以用它JSON_NUMERIC_CHECK来解决这个问题,但是这个方法似乎没有这样的选择Response::json().如何确保数字字段作为数字而不是字符串返回?
Kir*_*chs 23
你实际上可以通过该选项.如果我们看一下JsonResponse类的源代码,你可以传递json_encode选项作为最后一个参数.
它看起来像这样
return Response::json($properties, 200, [], JSON_NUMERIC_CHECK);
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
return Response::make(
$properties->toJson(JSON_NUMERIC_CHECK),
200,
['Content-Type' => 'application/json']
);
Run Code Online (Sandbox Code Playgroud)
注意:如果$properties不是Elequoent模型,那么它必须至少实现JsonableInterface
以及:
return Response::make(
json_encode($properties->toArray(), JSON_NUMERIC_CHECK),
200,
['Content-Type' => 'application/json']
);
Run Code Online (Sandbox Code Playgroud)
该的toJSON()雄辩方法只是包装json_encode()并将其传递模型的数组.我建议使用前两个选项之一.
小智 7
使用方法setEncodingOptions的JsonResponse:
return response()->json($properties)->setEncodingOptions(JSON_NUMERIC_CHECK);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7140 次 |
| 最近记录: |