nas
nas

Reputation: 2417

How to convert json Request to an array in symfony?

I am trying to convert the JSON Request $request to an array.

I have output something like this:

^ Symfony\Component\HttpFoundation\Request {#45
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#74
    #parameters: array:3 [
      "_route" => "app_movie_create"
      "_controller" => "App\Controller\MovieController::create"
      "_route_params" => []
    ]
  }
  +request: Symfony\Component\HttpFoundation\ParameterBag {#96
    #parameters: []
  }
  +query: Symfony\Component\HttpFoundation\ParameterBag {#69
    #parameters: array:1 [
      "title" => "Homecoming"
    ]
  }

I have seen some tutorials giving following solutions.

 $data = json_decode($request->getContent(), true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
        }

But I am getting null in my case.

I can do like this. $request->get('title');

Upvotes: 2

Views: 5536

Answers (2)

Undiscouraged
Undiscouraged

Reputation: 1125

Because the $request is a Symfony\Component\HttpFoundation\Request you can:

$data = $request->toArray();

to get an array containing the payload.

It does JSON de-serialization under the hood when the request content is properly declared to be JSON via the respective headers.

This is the preferred Symfony way in contrast to json_decode() manually.

Upvotes: 3

Dirk Scholten
Dirk Scholten

Reputation: 1048

$request->request->all() will return you an array of all the parameters that were sent along in the request. $request->query->all() will return you an array of all the query parameters that were sent.

json_decode($request->getContent()) would only work if the person who sends the request is sending you a json string in the raw body. In your case (since you can use $request->get('title');), this wasn't happening. The request just contains some parameters and no raw json body.

Upvotes: 3

Related Questions