0

I am not able to convert magento 2 JSON response into array. Can you please help in short out this problem?

Here is my code:

$url = 'http://example.com/api/coop';
$post = [
        'firstname' => $userDetail->firstname,
        'lastname'  => $userDetail->lastname,
        'email'     => $userDetail->email,
        'password'  => $userDetail->password
    ];
$this->curlClient->post($url, $post);
$responseCurl = $this->curlClient->getBody();
print_r($responseCurl);
die();

Output:

{"coop_id":"COOP33"}

I have to use coop_id value somewhere in my logic. Thanks in advance.

1

You can check in PHP sandbox, example below.
Show example

<?php

$jsonString = '{"coop_id":"COOP33"}';

$stdClass = json_decode($jsonString);
echo $stdClass->coop_id; //COOP33

$array = json_decode($jsonString, true);
echo $array['coop_id']; //COOP33
0
 $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array
0

You can use json_decode as follows.

<?php
    $json = $responseCurl;    
    $array = json_decode($json, true);
    $coop_id = $array['coop_id'];
?>
  • Thanks for reply soon! But its not working for me. – Pankaj Sharma Apr 24 '18 at 8:29
  • use var_dump(json_decode($json, true)); to see your values. – Pallavi Apr 24 '18 at 8:39
  • @PankajSharma Did you assign response to $json variable ? – Kishan Patadia Apr 24 '18 at 8:47
  • @KishanPatadia I am sending curl response in JSON format. – Pankaj Sharma Apr 24 '18 at 9:41
  • @PankajSharma Please try updated answer code – Kishan Patadia Apr 24 '18 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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