samedi 30 janvier 2016

Distinguish between JSON object and JSON array in Laravel

I need to validate a JSON payload to contain a JSON object for particular field. As far as I can see, both JSON objects and JSON arrays are converted to PHP arrays in Laravel's Illuminate\Http\Request

See the example below.

Controller.php

public 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 is the function that get hits on an HTTP request.

Here is a sample request and response from Controller.php

Request

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

Response

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

Is there a way I can validate fields obj1 and obj2 to only contain JSON objects here?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VxHjP0
via IFTTT

Aucun commentaire:

Enregistrer un commentaire