【问题标题】:Distinguish between JSON object and JSON array in LaravelLaravel 中 JSON 对象和 JSON 数组的区别
【发布时间】:2016-01-31 03:47:42
【问题描述】:

我需要验证 JSON 有效负载以包含特定字段的 JSON 对象。据我所知,在 Laravel 的Illuminate\Http\Request 中,JSON 对象和 JSON 数组都转换为 PHP 数组

请看下面的例子。

Controller.php

private static function getType($o) {
    if (is_object($o)) {
        return "Object";
    } else if (is_array($o)) {
        return "Array";
    }
    return "Unknown";
}

public function test(Request $request) {
    $input = $request->all();
    $response = [];
    foreach ($input as $key => $value) {
        $response[$key] = Controller::getType($value);
    }
    return response()->json($response);
}

test 是获得 HTTP 请求命中的函数。

这是来自 Controller.php

的示例请求和响应

请求

{
    "obj1": {},
    "obj2": {
        "hello": "world"
    },
    "arr1": [],
    "arr2": ["hello world"]
}

回应

{
  "obj1": "Array",
  "obj2": "Array",
  "arr1": "Array",      
  "arr2": "Array"
}

有没有一种方法可以验证字段 obj1obj2 仅包含 JSON 对象

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    Laravel 的 Illuminate\Http\Request 使用

    解码 json 函数中的 JSON 请求

    json_decode($this->getContent(), true)

    true 用于第二个参数$assoc 使json_decode 将所有对象转换为关联数组。

    我对 Controller.php

    进行了以下更改
    $input = $request->all();
    

    改为

     $input = json_decode($request->getContent());
    

    这是来自已修改 Controller.php

    的示例请求和响应

    请求

    {
        "obj1": {},
        "obj2": {
            "hello": "world"
        },
        "arr1": [],
        "arr2": ["hello world"]
    }
    

    回应

    {
      "obj1": "Object",
      "obj2": "Object",
      "arr1": "Array",
      "arr2": "Array"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 2011-07-31
      • 2018-02-23
      • 2014-07-02
      • 2017-03-27
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多