将获取的 JSON 保存到变量中

问题描述 投票:0回答:7

我正在尝试将 JSON 保存到变量中,但似乎我不理解这里的所有内容。我按照我喜欢的方式在控制台中显示了一次 JSON,但是当我尝试稍后再次调用它时,它只返回 Promise。如何将 JSON 保存到变量中,以便稍后可以使用 JSON 中的对象?

var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);
javascript json fetch-api
7个回答
29
投票

fetch API 是基于 Promise 的,并且总是返回一个新的 Promise,无论是已解决还是已拒绝。您有多种选择来返回结果。

异步/等待

async function getData(url) {
  const response = await fetch(url);

  return response.json();
}

const data = await getData(url);

console.log({ data })

回调

function getData(url, cb) {
  fetch(url)
    .then(response => response.json())
    .then(result => cb(result));
}

getData(url, (data) => console.log({ data }))

10
投票
let jsondata;    
fetch(url).then(
        function(u){ return u.json();}
      ).then(
        function(json){
          jsondata = json;
        }
      )

基本上,一旦承诺用实际数据解析,您就需要分配您的

jsondata
变量。目前,您将整个承诺分配给您的
jsondata
变量,这不是您想要的。


1
投票

您可以在 fetch 函数之外创建一个单独的函数来处理 json 数据,如下面的代码所示,fetch 函数将完整的 json 对象传递给另一个名为“data_function”的函数,我们可以通过此“data_function”继续处理 JSON 对象.

//fetch function
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
data_function(json); //calling and passing json to another function data_function
}
)

//another functions
function data_function(data){
alert(data.length); 
}

0
投票

另一种选择是使用回调作为参数,这样您就不会将变量暴露给全局范围。

function getFromAPI(url, callback){
  var obj;
  fetch(url)
    .then(res => res.json())
    .then(data => obj = data)
    .then(() => callback(obj))
 }

getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);

function getData(arrOfObjs){
  var results = "";
  arrOfObjs.forEach( (x) => {
    results += "<p> Id: " + x.id + "<ul>"
    Object.keys(x).forEach( (p) => {
        results += "<li>" + (p + ": " + x[p]) + "</li>";
    });
    results += "</ul> </p> <hr>"
  })
  results += "";
  document.getElementById("myDiv").innerHTML = results;
}

http://jsfiddle.net/5gch2yzw/


0
投票

在此示例中,您可以创建另一个异步函数

getData()
,并将从获取的 URL 中获取的数据添加到全局变量中。

当调用

getData()
函数时,它会使用
fetchData()
函数从提供的 URL 异步获取城市数据。成功获取数据后,会将其添加到全局变量
citiesData
,您可以在代码的其他部分使用此数据。

async function fetchData(url) {
    const response = await fetch(url);
    const data = await response.json();
    return data;
}

const citiesData = [];
const url = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

// Fetch data only once
async function getData() {
    const data = await fetchData(url);
    citiesData.push(...data);
}

getData();


console.log(citiesData);

0
投票

模块中的新顶层(在 Nodejs 18+ 中)

  let json="";

  const getJson = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1")
    return await response.json()       
  }
  
  json = await getJson()
  console.log(json.title)//prints: sunt aut facere repellat provident
  //console.log(json)

适用于 file.mjs,但不适用于 file.js!


-1
投票

最简单的方法是使用 async/await 方法。

只需将以下代码复制并粘贴到您的 Chrome 开发控制台中即可看到魔法:

async function githubUsers() {
            let response = await fetch('https://api.github.com/users')
            let users = await response.json()
            console.log(users)
    }

githubUsers()
© www.soinside.com 2019 - 2024. All rights reserved.