如何解析 fetch JSON return 并将元素放入 HTML 页面?

How can I parse fetch JSON return and put elements in to HTML page?

使用 Javascript 获取 api 我有一个 HTML 页面如下:

<body>

<div> <button onclick="github();">Get</button> </div>

<div id ="resp">    </div>
</body>

和一个Javascript函数如下:

<script type="text/javascript">
  function github() {
  fetch('https://api.github.com/users/KrunalLathiya')
  .then(response => response.json())
  .then(data => {
    console.log(JSON.stringify(data)) // Prints result from `response.json()` in getRequest
    const obj = JSON.stringify(data)
    document.getElementById("resp").innerHTML = obj["html_url"]
    })
  .catch(error => console.error(error))
   }
  </script>

returned json 在控制台中打印正常,但在 resp div 中显示为 "undefined" 或者,尝试不同的方法 object[Object]

如何遍历 json return 并打印 html 页面上的元素?然后,通过扩展,使用 Python Flask 应用程序?谢谢!

您错误地将返回的数据字符串化,然后将其(字符串)视为对象。这是打印返回数据的所有键和值的简单通用代码段。

github();

function github() {
  const responseContainer = document.querySelector("#resp");
  fetch('https://api.github.com/users/KrunalLathiya')
    .then(response => response.json())
    .then(data => {
      Object.entries(data).forEach( ([key, value]) => 
        responseContainer.textContent += `${key}: ${value}\n`
      )  
    })
    .catch(error => console.error(error))
}
<pre id="resp"></pre>