使用Javascript浏览器获取YAML或MsgPack

问题描述

我知道如何使用Fetch API来获取JSON:

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

我试图复制相同的东西以获取MsgPack或YAML数据,但是我的所有尝试均以失败告终。我显然知道如何反序列化数据,但是我怀疑我对完全没有把握的链式承诺感到有些困惑。由于没有response.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-yamlhttps://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