Search code examples
javascriptjsonfetch

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


Solution

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