Json path to get api value

Asked

Viewed 439 times

1

How to take the value of low of the following api:

[{"idreg":"257052","code":"USD","codein":"BRL","name":"D\u00f3lar Comercial",      
  "high":"3.4026","pctChange":"1.143","open":"0","bid":"3.3703","ask":"3.3713",  
  "timestamp":"1481828340000","low":"3.367","notFresh":"0","varBid":"0.0381",   
  "create_date":"2016-12-15 17:30:02"}] 

I don’t quite understand what the rules of the road are json but I tried it this way:

<?php    
    $json_file = file_get_contents("https://economia.awesomeapi.com.br/json/USD-BRL/1");   
    $dados = json_decode($json_file);    
    echo $dados->low;
?>

What I’m doing wrong?

2 answers

2

You can do it like this:

$json_file = file_get_contents("https://economia.awesomeapi.com.br/json/USD-BRL/1");
$dados = json_decode($json_file);
echo $dados[0]->low; // 3.367

DEMONSTRATION

You can fetch the data as an array as well:

...
$dados = json_decode($json_file, true);
echo $dados[0]['low']; // 3.367

Note that in the data format:

Array
(
    [0] => Array
        (
            [idreg] => 257052
            [code] => USD
            [codein] => BRL
            [name] => Dólar Comercial
            [high] => 3.4026
            [pctChange] => 1.143
            [open] => 0
            [bid] => 3.3703
            [ask] => 3.3713
            [timestamp] => 1481828340000
            [low] => 3.367
            [notFresh] => 0
            [varBid] => 0.0381
            [create_date] => 2016-12-15 17:30:02
        )

)

These are all in key 0 of our main array, and these in turn are an associative array if json_decode($json_file, true) otherwise they are an object by default json_decode($json_file), and you must access $dados[0]->PROPRIEDADE_QUE_QUERES

  • great explanation :D, vlw

  • (: hehe obagdo @picossi

2


<?php

$json_file = file_get_contents("https://economia.awesomeapi.com.br/json/USD-BRL/1");   
$dados = json_decode($json_file);

echo $dados[0]->low;


?>
  • why this "[0]"

  • 1

    It is the index. Think that the returned json could have several lines, the number between [] means what it is. In this case it was only one, so it is "0"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.