1

I have an API which will return an array to me. I tried to use fetch API to get the array back. I know that if I use fetch to acquire some data, the real body in the response is ReadableStream. I usually to deal with it by response.json() in then function if data is json. What I don't know is how to deal with array data?

6
  • 1
    Going to need to see what your API represents an Array as, and how you are currently attempting to fetch the data, using the .json() method would properly format and return an array value Commented May 24, 2017 at 18:55
  • What's "array data" if not JSON? CSV? Commented May 24, 2017 at 18:55
  • confused What specifically is the API sending back? Not JSON? Commented May 24, 2017 at 18:56
  • Won't you just need to parse the JSON? Commented May 24, 2017 at 18:56
  • 2
    You can also use .text() and parse anything yourself, in any format that you find a parser for. Commented May 24, 2017 at 18:57

1 Answer 1

6

If your API is not returning a JSON array [1,2,3] then you can use the .text function to get the raw value:

fetch('/api/text').then(function(response) {
  return response.text()
}).then(function (text) {
  // parse the text here how you want, for csv:
  // return text.split(',')
})

Otherwise you can simply just use the .json method to get the array value.

The ArrayBuffer that you mention is to read a binary buffer, it can be useful for fetching songs or etc... If your API is returning this, I would check out the link to see what you can do. You will most likely be required to decode the buffer and how that is done is completely dependent on how your API is encoding it and I cannot answer that without more detail regarding your API response.

Sign up to request clarification or add additional context in comments.

1 Comment

Just realized that .split(',') turns the text into array :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.