Home > Net >  How to manipulate API results in JavaScript?
How to manipulate API results in JavaScript?

Time:02-10

I am learning to use an API and I need some help.

I chose yahoo finance API and I'm trying to interpret the results. For this, I want to just access some of the data and display it on screen. I don't really know how I should do this. What is the correct method?

var configuration = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "yh-finance.p.rapidapi.com",
    "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
  },
};
var url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

var name = document.querySelector("stock-name");
var price = document.querySelector("stock-price");
var high = document.querySelector("stock-high");
var currency = document.querySelector("stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: "   response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  name.innerHTML = "Stock name:"   Object.keys(stockData.meta.symbol);
  price.innetHTML = "Stock's price:"   stockData.priceHint;
  high.innerHTML = "Stock's high:"   stockData.indicators.quote[0].high[0];
  currency.innerHTML = "Stock's currecy:"   stockData.meta.currency;
}
 </div>
      <div><h3 id = "stock-name"></h3>
        <h3 id = "stock-price"></h3>
        <h3  id = "stock-high"></h3>
        <h3 id = "stock-currency"></h3>
      </div>

I am not a fan of Jquery.

I tried accessing the data from API in the console with:

console.log(Object.keys(stockData.chart.result[0].meta));

console.log(Object.values(stockData.chart.result[0].meta));

to see if I can access it like this, but I can't access one element, like meta[x], only the whole array.

Does anyone know where can I learn more about manipulating data from API? I couldn't find any good information...

CodePudding user response:

{
  "chart": {
    "result": [
      {
        "meta": {
          "currency": "USD",
          "symbol": "AMRN",
          "exchangeName": "NGM",
          "instrumentType": "EQUITY",
          "firstTradeDate": 733674600,
          "regularMarketTime": 1644440402,
          "gmtoffset": -18000,
          "timezone": "EST",
          "exchangeTimezoneName": "America/New_York",
          "regularMarketPrice": 3.69,
          "chartPreviousClose": 3.53,
          "priceHint": 4,
          "currentTradingPeriod": {
            "pre": {
              "timezone": "EST",
              "end": 1644503400,
              "start": 1644483600,
              "gmtoffset": -18000
            },
            "regular": {
              "timezone": "EST",
              "end": 1644526800,
              "start": 1644503400,
              "gmtoffset": -18000
            },
            "post": {
              "timezone": "EST",
              "end": 1644541200,
              "start": 1644526800,
              "gmtoffset": -18000
            }
          },
          "dataGranularity": "1d",
          "range": "1d",
          "validRanges": [
            "1d",
            "5d",
            "1mo",
            "3mo",
            "6mo",
            "1y",
            "2y",
            "5y",
            "10y",
            "ytd",
            "max"
          ]
        },
        "timestamp": [
          1644417000,
          1644440402
        ],
        "indicators": {
          "quote": [
            {
              "open": [
                3.559999942779541,
                3.559999942779541
              ],
              "close": [
                3.690000057220459,
                3.690000057220459
              ],
              "high": [
                3.740000009536743,
                3.740000009536743
              ],
              "volume": [
                2084300,
                2089304
              ],
              "low": [
                3.559999942779541,
                3.559999942779541
              ]
            }
          ],
          "adjclose": [
            {
              "adjclose": [
                3.690000057220459,
                3.690000057220459
              ]
            }
          ]
        }
      }
    ],
    "error": null
  }
}

Sample response I got running your code

const metaData = stockData.chart.result[0].meta

metaData.currency //'USD'
metaData.regularMarketPrice //3.69

If you know the key you can directly get the value from it.

CodePudding user response:

you can simple make following changes in you JS file :

const configuration = {
    method: "GET",
    headers: {
      "x-rapidapi-host": "yh-finance.p.rapidapi.com",
      "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
    },
  };


const url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

const name = document.querySelector("#stock-name");
const price = document.querySelector("#stock-price");
const high = document.querySelector("#stock-high");
const currency = document.querySelector("#stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: "   response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  let metadata = stockData.chart.result[0].meta;  
  let indicators =  stockData.chart.result[0].indicators;
  name.innerText = "Stock name:"   metadata.symbol;
  price.innerText = "Stock's price:"   metadata.priceHint;
  high.innerText = "Stock's high:"   indicators.quote[0].high[0];
  currency.innerText = "Stock's currecy:"   metadata.currency;
}

here you can choose between innerHTML and innerText, as you just wanted to inject the values I have used the innerText.

  • Related