How to access JSON data in a branch template?

I am using Symfony2 and making a php curl request on api. I want to make sure that the results are returned in the correct form: as a json string (and not a php object or something else). The returned json string is consumed by renderAPIResults (), which uses the branch to "render" a JsonResponse. Is it possible?

Can I "visualize" the answer in renderAPIResultsor do I need to return JsonResponseand make it display it after being called from apiAction ()?

Is there symfony2 built-in functionality if someone calls template results.json.twigvs. results.html.twig, or is this naming convention just idiomatic?

I managed to get the results in results.html.twig by creating Response()in the method renderAPIResults(), but I was able to get the console.log()results from the file .jswhen returning the results as JsonResponse(). I could not analyze these results in any form or form in the template results.json.twigwhen I tried to “make” a in any way JsonResponse.

 //DefaultController.php
 public function curlRestRequest($apiQueryString, $jsonDecode = FALSE, array $post_data = null, $service_url = null){

    if(!$service_url) {
        $service_url = 'http://website.com/rest';
    }

    $curl = curl_init($service_url.$apiQueryString);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

    $curl_response = curl_exec($curl);

    if ($curl_response === false) {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    }
    curl_close($curl);

    if($jsonDecode)
    {
        $curl_response = json_decode($curl_response);
    }

    return $curl_response;
}

public function renderAPIResults($data, $asObject = FALSE, $template)
{
    if(!$template) {
        throw new Exception('Must provide a template name before rendering!');
    }

    if($asObject != TRUE) {
        // we want to cast to array since specified as OBJECT = FALSE, removing all instances of objects
        $dataArray = json_decode(json_encode($data), true);
        return $this->render($template, array('data' => $dataArray));
    } else { // Is JSON Decoded, if it is an object
        //just return json data, parse it in javascript instead of with template

        $response = new JsonResponse();
        $response->setData(array(
            'data' => $data
        ));
        return $response;
        //return $this->renderView($template, array('data' => $data));
        //or
        //$content = $this->render($template, array('data' => $data));
        //return new JsonResponse($content);
    }
}

public function apiAction($type, $query){
  $apiQueryString = '/search/' . $type . '?query=' . $query;

  //make a curl request
  $requestedResults = ($this->curlRestRequest($apiQueryString, TRUE));

  //return option three: (dont use any response object, and just pass, just pass curl-results directly)
  //note, currently, when set as true, its not rendered in the template, the template is not used
  $view = $this->renderAPIResults($requestedResults, TRUE, 'ApiBundle:API:results.json.twig');
  return $view;
}

This is the branch template:

//results.json.twig
{{ dump(data) }}

Basically, I ask:

How to use JsonResponse()in a method renderAPIResults()for rendering results.json.twigin the same method, returning this processed template so that could focus on the results json

Can I use JsonResponse()to render a template this way? Or do I need to use only the method Response()when rendering?

JsonResponse , ? .. {{ dump(results) }} javascript ?


EDIT: , .

json_decode ($ string, TRUE), , , , . json_decode, json, ?

, . JSON json_decode/

, , , , , JSON .

.

$requestedResults = ($this->curlRestRequest($apiQueryString, TRUE));
print_r($requestedResults);
//yields  Array
(
    [category] => 
    [executionTime] => 759
    [facets] => 
    [resultCount] => 8
    [searchCount] => 0
    [searchInfo] => 
    [searchResults] => Array
        (
            [0] => Array
                (
                    [description] => Gives instructions for 3 different in-class games.
                    [taxonomyDataSet] => {"course":[],"topic":[],"unit":[],"lesson":[],"subject":[],"curriculum":{"curriculumName":["Common Core State Standards - Math","Common Core State Standards - Math"],"curriculumCode":["CCSS.M.8.G.C.9","CCSS.M.7.G.B.6"],"curriculumDesc":["Solve real-world and mathematical problems involving area, volume and surface area of two- and three-dimensional objects composed of triangles, quadrilaterals, polygons, cubes, and right prisms.","Know the formulas for the volumes of cones, cylinders, and spheres and use them to solve real-world and mathematical problems."]}}
[thumbnail] => slides/thumbnail.jpg
                        [title] => Game Suggestions for Volume
                    )            
    )

" ", . , - DataSet , , .

$requestedResults = ($this->curlRestRequest($apiQueryString, TRUE));

    foreach ($requestedResults['searchResults'] as $resource) {
        $title = $resource["title"];
        $description = $resource["description"];
        $thumbnailUrl = $resource["thumbnails"]['url'];
        $taxonomyDataSet = json_decode($resource['taxonomyDataSet'],TRUE);
        $standard = $taxonomyDataSet['curriculum']['curriculumCode'];
        if(! file_exists($thumbnailUrl))
        {
            $thumbnailUrl = NULL;
        }

        $results[] = array($title,$description,$thumbnailUrl, $standard);
    }
print_r($results);

//yields
Array
(
[0] => Array
    (
        [0] => Game Suggestions for Volume
        [1] => Gives instructions for 3 different in-class games.
        [2] => 
        [3] => Array
            (
                [0] => CCSS.M.8.G.C.9
                [1] => CCSS.M.7.G.B.6
            )

    ))

, JSON, ?

, return $requestedResults->searchResults TWIG .

, , , API , , json_encoded, , , . , , , ?

+4
2

FOSRestBundle, JSON "". , , API REST.

Guzzle API . , ( ). , , $response = $guzzleClient->get($url, $options) $reponse->json() , API.

API , . FOSRestBundle + JMSSerializerBundle, JSON ( XML, , /api/users.xml XML , /api/users.json JSON).

, , , , , , .

0

, , :

, API , , JSON PHP, .

, JSON ; .

0

Source: https://habr.com/ru/post/1527376/


All Articles