简体   繁体   中英

How to get access Object from API response?

I want to access Object with data from API response.

Presently, the response in the console looks like this: 在此处输入图像描述

But I want to get this data: 在此处输入图像描述

This is browser script. Not NODE

My entire code...

const input = document.querySelector('input[type="file"]');

function getData(symbol) {
  return fetch(
    `https://cors-anywhere.herokuapp.com/` +
      `https://eodhistoricaldata.com/api/fundamentals/${symbol}?api_token=***************`,
    {
      method: "get",
    }
  )
    .then((data) => {
      if (!data.ok) {
        throw new Error("Symbol is 'empty'");
      }
      (data) => data.json();
      console.log(data);
      return data;
    })
    .catch((error) => {
      throw error;
    });
}

input.addEventListener(
  "change",
  function (e) {
    const reader = new FileReader();
    reader.onload = async function () {
      const symbolsArr = reader.result.split("\n").map((str) => str.trim());
      let json_file = await getData(symbolsArr[0]);
      saveFile(json_file, "json.txt", "text/plain");
      symbolsArr.forEach((element) => {});
    };
    reader.readAsText(input.files[0]);
  },
  false
);
function saveFile(content, fileName, contentType) {
  var a = document.createElement("a");
  var file = new Blob([content], { type: contentType });
  a.href = URL.createObjectURL(file);
  a.download = fileName;
  a.click();
}

I want to save the Object from the response to a json_file variable and then execute the saveFile method to save the file locally.

The data is returned from an API inside the body attribute of the response. Try printing

data.body

to the console.

Finally once the JSON is received, use the stringify function to parse the JSON into a string and then store it in the file.

var myJSON = JSON.stringify(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM