首页 > 解决方案 > Retrieve elements in js from a json object

问题描述

Im trying to get stock prices from this api: https://english.api.rakuten.net/apidojo/api/yahoo-finance1?endpoint=apiendpoint_a1e0ecc6-0a3a-43fd-8133-77a66d33f68c
In the web page you can see the json objects that getting historical data returns, even though Im using their fetch code to call the api, response is empty {}.
Does anyone know how to get the adjclose variable and store it in an array?

This is my code so far

    let symbol = "DIS";
    let unixTimeStamp = Math.round((new Date()).getTime() / 1000).toString();
    let url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-historical-data?frequency=1d&filter=history&period1=1&period2=" + unixTimeStamp + "&symbol=" + symbol;
    fetch(url, {
        "method": "GET",
        "headers": {
             "x-rapidapi-host": "apidojo-yahoo-finance-v1.p.rapidapi.com",
              "x-rapidapi-key": "Secret api key"
           }
    })
    .then(response => {

        console.log(response);

    })
    .catch(err => {
        console.log(err);
    });

标签: javascriptarraysjson

解决方案


From the MDN documentation,

"This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json()".

In your case, you need to call json() on your response to parse through it and then you can do something with that data.

 fetch(url, {
        "method": "GET",
        "headers": {
             "x-rapidapi-host": "apidojo-yahoo-finance-v1.p.rapidapi.com",
              "x-rapidapi-key": "Secret api key"
           }
    })
    .then(response => {
        response.json();
        console.log(response.json())
    })
    .then(data => {
        console.log(data)
    })
    .catch(err => {
        console.log(err)
    });

See Fetch docs: MDN Fetch Documentation


推荐阅读