Home > Back-end >  Getting the specific part of a JSON
Getting the specific part of a JSON

Time:01-08

I have an API and I use that API to get the exchange rates.

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://v6.exchangerate-api.com/v6/3307b104e7b3be179b55050e/latest/USD');
$currency = $res->getBody();

I want to get the conversion_rates data only from the JSON and ignore the rest.

I use Laravel.

CodePudding user response:

You need $res->json()['conversion_rates']

Calling it from tinker (just to test):

Http::withOptions(['verify' => false])
    ->get('https://v6.exchangerate-api.com/v6/3307b104e7b3be179b55050e/latest/USD')
    ->json()['conversion_rates'];

it gives back

=> [
     "USD" => 1,
     "AED" => 3.6725,
     "AFN" => 104.838,
     "ALL" => 106.8525,
     "AMD" => 482.8513,
     ...
   ]

Final solution, based on your editing:

$response = Http::withOptions(['verify' => false])
    ->get('https://v6.exchangerate-api.com/v6/3307b104e7b3be179b55050e/latest/USD');

$conversion_rates = $response->json()['conversion_rates'];

CodePudding user response:

might work

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://v6.exchangerate-api.com/v6/3307b104e7b3be179b55050e/latest/USD');

$data = $res->getBody()->getContents();
$dataArray = json_decode($data, true);
$rates = $dataArray['conversion_rates'] ?? [];
  •  Tags:  
  • Related