我知道如何使用 Fetch API 来获取 JSON:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
我试图复制相同的东西来获取 MsgPack 或 YAML 数据,但我的所有尝试都失败了。我显然知道如何反序列化数据,但我怀疑我对我没有完全掌握的链式 promise 感到有点迷茫。由于没有 response.yaml(),我需要一个额外的步骤,但我无法让它工作。我尝试使用 response.body() 和 response.blob()。每次我这样做时,控制台日志时都没有可用数据。我认为这意味着我的数据仍然是一个 promise ,而不是通过回调进行处理和调用。
我试过这样的事情:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(data => console.log(deserialize(data)));
或:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(raw => deserialize(raw))
.then(data => console.log(data));
此处 deserialize
是任一格式的反序列化/解码函数的占位符。
任何人都有使用 YAML 的示例(我怀疑比 MsgPack 更受欢迎)。
最佳答案
也许这个 npm 包可以帮助您解析 yaml 数据:https://www.npmjs.com/package/js-yaml , https://github.com/nodeca/js-yaml .
例子.yaml:
docker:
- image: ubuntu:14.04
- image: mongo:2.6.8
command: [mongod, --smallfiles]
- image: postgres:9.4.1
这对我有用:
fetch('/example.yaml')
.then(res => res.blob())
.then(blob => blob.text())
.then(yamlAsString => {
console.log('yaml res:', yamlAsString)
})
.catch(err => console.log('yaml err:', err))
首先我们将结果转换为 Blob。之后,我们对其调用 text() 方法,将 blob 转换为字符串。
关于javascript - 在 Javascript(浏览器)中获取 YAML 或 MsgPack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63953024/