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

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

Here is a sample request and response from Controller.php

Request

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

Response

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

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire