4

I know how to fetch JSON with the Fetch API like this:

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

I tried to replicate the same thing to get MsgPack or YAML data, but all my attempts have failed. I obviously know how to deserialize data, but I suspect I feel a bit lost with chained promises which I don't fully grasp. Since there is no response.yaml(), I need to us an extra step but I can't make it work. I tried with response.body() and response.blob(). Each time I do it, no data is available at the time of the console log. Which I assume means that my data is still a promise instead of being processed and called with the callback.

I have tried things like:

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

or:

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

Here deserialize is a placeholder for the deserialize/decode function for either format.

Anybody has an example using YAML (I suspect more popular than MsgPack).

Mig
  • 662
  • 4
  • 13

1 Answers1

4

Maybe this npm package can help you with parsing yaml data: 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

This works for me:

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))

First we convert the result to a Blob. After that we call the text() method on it which converts the blob to a string.

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

AtaiLo
  • 101
  • 3
  • Thanks @AtaiLo. Like I said I don't have problems with deserializing the data. If I had the YAML already in a String I would be fine. My problem is fetching a YAML file and get the string with the Fetch API specifically. Thank you for trying to help though. – Mig Sep 18 '20 at 11:51
  • Hey thanks. I did not try text(). I need to check if it works for msgpack since it is binary and not text. – Mig Sep 18 '20 at 17:54