【问题标题】:Fetch YAML or MsgPack in Javascript (Browser)在 Javascript(浏览器)中获取 YAML 或 MsgPack
【发布时间】:2021-01-05 05:33:50
【问题描述】:

我知道如何使用 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 更受欢迎)。

【问题讨论】:

    标签: javascript json yaml fetch msgpack


    【解决方案1】:

    也许这个 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

    【讨论】:

    • 谢谢@AtaiLo。就像我说的那样,我在反序列化数据方面没有问题。如果我已经在字符串中拥有 YAML,我会很好。我的问题是获取 YAML 文件并专门使用 Fetch API 获取字符串。不过,感谢您提供帮助。
    • 嘿,谢谢。我没有尝试文本()。我需要检查它是否适用于 msgpack,因为它是二进制而不是文本。