Adam
Adam

Reputation: 1159

Array Index is empty, accessing JSON object

I am calling the following API url: https://api.gemini.com/v1/trades/btcusd?timestamp=1518710400&limit_trades=1

This returns the following JSON:

[
     {
         "timestamp":1518710409,    
         "timestampms":1518710409004,
         "tid":3051346543,
         "price":"9837.17",
         "amount":"0.00118501",
         "exchange":"gemini",
         "type":"sell"
      }
]

When I try to access the 'price' object from the json string like so:

$response = $client->request('GET', 'https://api.gemini.com/v1/trades/btcusd?timestamp=1518710400&limit_trades=1');
$body     = json_decode($response->getBody());

A var_dump() returns:

array(1) { [0]=> object(stdClass)#85 (7) { ["timestamp"]=> int(1518710409) ["timestampms"]=> float(1518710409004) ["tid"]=> float(3051346543) ["price"]=> string(7) "9837.17" ["amount"]=> string(10) "0.00118501" ["exchange"]=> string(6) "gemini" ["type"]=> string(4) "sell" } } 

But I'm getting the following error:

Notice: Trying to get property of non-object in (file path) on line 130

Line 130 being

echo $body->price

Why is $body->price not a valid accessor of the 'price' returned from the JSON string?

Upvotes: 0

Views: 139

Answers (1)

Andrew Cotton
Andrew Cotton

Reputation: 425

$body is an array, so you would need to do the following since it is the first item in that array:

$body[0]->price;

Upvotes: 2

Related Questions