简体   繁体   中英

Getting the specific part of a JSON

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.

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'];

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'] ?? [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM