简体   繁体   English

Laravel(Request $ request)处理如何检查输入是否为正确的json格式?

[英]Laravel (Request $request) handling how to check if input is in the correct json format?

So I'm building an api that accepts json input, and catching it in the controller with Request: 所以我正在构建一个接受json输入的api,并使用Request在控制器中捕获它:

{
    "val1": "11",
    "val2": "1000",
    "val3": "1001010",
    "val4": "1001"
}

However I need to catch a condition when the user didn't use proper json, say like this: 但是,当用户未使用正确的json时,我需要抓住一个条件,像这样说:

{
    "val1": "11",
    "val2": "1000",
    "val3": "1001010"
    "val4": "1001"
}

When I return $request on wrong input format, I got empty array. 当我以错误的输入格式返回$ request时,得到了空数组。 However I have tried using isset() , empty() , count() on request but it still didn't check the parameters. 但是我尝试根据要求使用isset()empty()count() ,但是它仍然没有检查参数。

public function foo(Request $request)
{
   if(jsoniswrong($request)){return 'false';}
}

I need a way to check the request variable without having to call each values, how do I do this? 我需要一种无需调用每个值即可检查请求变量的方法,该怎么办?

edit: I ended up using this which is simpler. 编辑:我最终使用了它,这更简单。 I just realized in Laravel, empty($request) will never return true because even on a bad request it still have objects other than the actual input data. 我刚刚在Laravel中意识到,empty($ request)永远不会返回true,因为即使在错误的请求下,empty($ request)仍然具有除实际输入数据以外的对象。 To get the input data, use all(). 要获取输入数据,请使用all()。 This solved my problem. 这解决了我的问题。

    if(empty($request->all())){
        return false;
    }

You may validate an incoming request for json using the validate() method. 您可以使用validate()方法验证 json的传入request You can achieve this by doing the following: 您可以通过执行以下操作来实现:

public function foo(Request $request)
{
    $data = $request->validate([
        'json' => 'required|json'
    ]);

    // continue process
}

Here, we use the required rule to make sure that the json has been passed. 在这里,我们使用必需的规则来确保已传递json We then use the json rule which checks if valid json has been passed. 然后,我们使用json规则检查是否已传递有效的json A | A | is used to separate validation rules. 用于分隔验证规则。

If the json is not valid, data about the error will be returned. 如果json无效,则将返回有关错误的数据。

Please note , you must name the field/key of the incoming json data the same as the key within the validate() array. 请注意 ,您必须将传入json数据的field/key命名为与validate()数组中的关键字相同。 eg if the field/key is called data it must be ['data' => 'required|json'] . 例如,如果field/key被称为data则必须为['data' => 'required|json']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM