Select JS data

Asked

Viewed 42 times

-2

I’m having the following difficulty. When making the API request, comes all the data and I’d like to select the data I want.

function fazerRequisicao() {
    ulr = 'https://economia.awesomeapi.com.br/last/USD-BRL'

    var url = document.getElementById('url').value;

    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, false);

    xhttp.send();//A execução do script pára aqui até a requisição retornar do servidor

    document.getElementById("resposta").innerHTML = xhttp.responseText;

    console.log(resposta)
}

Returns

{"USDBRL":{"code":"USD","codein":"BRL","name":"Dólar Americano/Real Brasileiro","high":"5.1273","low":"5.0755","varBid":"0.0037","pctChange":"0.07","bid":"5.1125","ask":"5.115","timestamp":"1626469196","create_date":"2021-07-16 17:59:58"}}

I would like to know how to display only Bid Dollar R$ 5.1125

  • Have tried using innerhtml.substring(1, 50) at the end of the instruction

1 answer

0


You need parse the result and with it, access the desired field:

     
        var url = 'https://economia.awesomeapi.com.br/last/USD-BRL'
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, false);
    xhttp.send();
    resposta = xhttp.responseText;
    r = JSON.parse(resposta); //JSON.parse transforma a string (JSON) 'resposta' em um objeto javascritp
    dolar_bid = r.USDBRL.bid //aqui, dentro o objeto criado, encontro a propriedade desejada
    document.getElementById("resposta").innerHTML = dolar_bid
<div>R$ <span id="resposta"></span></div>

Browser other questions tagged

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