Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with JSON coming from api-platform

I've installed the api-platform demo on a server and I did a client app (working with Symfony 3.3) and I want to display the response in a classic view (Twig).

Everything's working fine : I can request and retrieve the response.

But here's where i'm stuck : when I dump the response in my view I got this

 {"@context":"\/contexts\/Book","@id":"\/books","@type":"hydra:Collection","hydra:member":[{"@id":"\/books\/1","@type":"Book","id":1,"isbn":"9783161484100","title":"1st Book","description":"This is my first book synopsis","author":"Hemingroad","publicationDate":"2018-02-16T14:15:58+00:00","reviews":[]}],"hydra:totalItems":1}

Here's my controller's method :

 //...
 use GuzzleHttp\Client;

public function newAction(Request $request)
{
     //initialize client API
    $client = new Client([
        'base_uri' => 'http://my.apidomain.com/',
        'timeout'  => 2.0,
    ]);

    //request to API
    $dataBooks = $client->request('GET', 'books', ['auth' => ['login', 'p@$$w0rd']]);
    $listBooks = $dataBooks->getBody()->getContents();
    return $this->render('book/new.html.twig', array(
        'listBooks'   => $listBooks
    ));
}

I've also tried to json_decode and using JMSSerializer on $listBooks. I got a beautiful object but I still cant access the JSON attribute's like ISBN, title by doing something like

 {% for book in listBooks %}
      {{ dump(book.title) }}
       <!-- .... -->
 {% endfor %}

Here's what I got when I json_decode $listBooks :

  {{ dump(listBooks) }}

enter image description here

I got an error when I try to access every field like this

  {{ dump(listBooks.@id) }}
  {{ dump(listBooks['hydra:member']) }}
  ....

Am I missing something ?

Thanks

like image 330
skytorner Avatar asked Mar 07 '23 21:03

skytorner


1 Answers

$dataBooks->getBody()->getContents(); returns a string, as described in Guzzle's documentation, so you need to use json_decode.

$listBooks = json_decode($listBooks); returns an object. In Twig you can use the dot notation to access methods and properties of an object, e.g. {{ listBooks.myProp }}. But because hydra:member includes a special character (:), you need to use Twig's attribute function, as described in Twig's documentation:

{{ attribute(listBooks, 'hydra:member') }}

Another approach is to do $listBooks = json_decode($listBooks, true); so that you get an associative array instead of an object. Then you can use the bracket notation in Twig:

{{ listBooks['hydra:member'] }}

I would prefer this second approach, because in my opinion {{ listBooks['hydra:member'] }} is much clearer and cleaner than {{ attribute(listBooks, 'hydra:member') }}.

like image 90
Matias Kinnunen Avatar answered Mar 10 '23 12:03

Matias Kinnunen