如何操纵 API 结果为 JavaScript?

How to manipulate API results in JavaScript?

我正在学习使用 API,我需要一些帮助。

我选择了 yahoo finance API,我正在尝试解释结果。为此,我只想访问一些数据并将其显示在屏幕上。我真的不知道我该怎么做。正确的方法是什么?

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>

我不是Jquery的粉丝。

我尝试在控制台中访问来自 API 的数据:

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

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

看看能不能这样访问,但是我不能访问一个元素,比如meta[x],只能访问整个数组。

有谁知道我在哪里可以了解更多关于从 API 处理数据的信息?我找不到任何好的信息...

{
  "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
  }
}

我得到的示例响应 运行 你的代码

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

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

如果您知道密钥,您可以直接从中获取值。

您可以简单地在您的 JS 文件中进行以下更改:

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;
}

这里你可以在 innerHTML 和 innerText 之间选择,因为你只是想注入我使用 innerText 的值。