在Javascript(浏览器)中获取YAML或MsgPack



我知道如何使用fetch API获取JSON,如下所示:

fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

我试图复制同样的东西来获取MsgPack或YAML数据,但所有的尝试都失败了。我显然知道如何反序列化数据,但我怀疑我对没有完全掌握的连锁承诺感到有点迷失。由于没有响应.yaml((,我需要多走一步,但我无法使其工作。我尝试了response.body((和response.blob((。每次我这样做,在控制台日志时都没有可用的数据。我认为这意味着我的数据仍然是一个承诺,而不是通过回调进行处理和调用。

我试过这样的东西:

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.


example.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转换为字符串。

https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

最新更新