4

I´m getting data from web service in Drupal 8:

$uri = "http://localhost:8888/drupal8/tipo_receta.json";
 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'application/json')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }else{
        print $data;
    }
  }
  catch (RequestException $e) {
      return FALSE;
  }

I have this JSON source:

{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
            "ingredient_name": "manzana",
            "ingredient_value": "300 grs. De Manzana"
        }
    ]
}

This is my result on the page:

C:\wamp64\www\drupal8\core\themes\bartik\bartik.theme:142:string '{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
         '...

How can i get an array so i could filter the data like this?

if($data['recipe_doc_id'] == "1"){
print $data['recipe_title'];
}
1

1 Answer 1

12

Use the Json::decode() method:

use Drupal\Component\Serialization\Json;

...

$decoded = Json::decode($data);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.