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

标签 javascript json yaml fetch msgpack

我知道如何使用 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 转换为字符串。

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

关于javascript - 在 Javascript(浏览器)中获取 YAML 或 MsgPack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63953024/

相关文章:

json - 使用 VSTS Rest API,如何更新 Markdown 小部件?

javascript - js-yaml -> 解析 ruby​​ 类型

javascript - laravel 自动完成 TextView

javascript - 在 javascript 中为 document.location 创建钩子(Hook)

javascript - 使用数字数组和 json 元素数组时,D3 条形图看起来不同

javascript - 从本地 Windows 存储文件夹中读取 js 中的文件

python - windows下python的yaml和编译libYaml

mongodb - 为什么我收到错误 "db_name must be a string or symbol"?

javascript - 如何扩大光华的半径?

javascript - 如何将同一小工具的多个实例分开