Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - 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: enter image description here

But I want to get this data: enter image description here

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("
").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.

question from:https://stackoverflow.com/questions/65937556/how-to-get-access-object-from-api-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...