gpt4 book ai didi

javascript - 如何从 JavaScript 输出 JSON 输出,以便将其识别为 JSON?

转载 作者:行者123 更新时间:2023-11-30 15:10:57 28 4
gpt4 key购买 nike

编辑:在与 guest271314 交流后,我意识到问题的措辞(在我的问题正文中)可能具有误导性。我保留了旧版本并更好地改写了新版本


背景: 从远程服务器获取 JSON 时,响应 header 包含一个 Content-Type: application/json 条目,提示浏览器将内容呈现为 JSON。这使 Chrome extensions或 native Firefox 功能来格式化输出:

enter image description here

我的问题:我想通过首先获取内容然后推送它来使用 JavaScript 提供的 JSON 获得相同的呈现(由浏览器完成)进入DOM。这行不通,我只能得到一个 JSON 字符串,呈现为字符串。JSON 呈现为字符串,浏览器没有格式化。

到目前为止我的想法:看来我没能做到

  • 将 JSON 输出为不带分隔符的字符串
  • 通知浏览器内容是JSON

我试过的代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<!-- here I am trying to simulate the response headers so that the
browser is hinted of the content type -->
<meta http-equiv="content-type" content="application/json; charset=UTF-8"/>
</head>
<body>
<div id='root'></div>
<script>
fetch('https://httpbin.org/get')
.then(function (r) {
if (r.ok) {
return r.json()
}
throw new Error('response was not ok: ' + r.statusText)
})
.then(function (text) {
// here I am stringyfying the JSON Object and replacing a DOM
// element with it (including the delimiters). The string is
// unfortunately quote-delimited
document.getElementById('root').outerHTML = JSON.stringify(text)
})
.catch(function (err) {
console.log(err)
})
</script>
</body>
</html>

同源效果:

enter image description here

是否有可能从 JS 实现与直接在浏览器中查询源代码相同的效果?让 JavaScript 生成的 JSON 由浏览器自己的机制(内置-在或通过扩展)?

最佳答案

好吧,您的浏览器扩展无法捕捉到这一点。我没有看到任何选择。当 JavaScript 被执行时, header 已经发送,所以我想,您的扩展已经退出游戏。

顺便说一下,stringify() 函数工作正常。您想要的是人类可读的输出。

你有没有想过像

这样的 JavaScript 代码高亮器

应该有一个像您的浏览器扩展一样支持 JSON 呈现的。

关于javascript - 如何从 JavaScript 输出 JSON 输出,以便将其识别为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45118776/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com