admin管理员组

文章数量:1290946

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?

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?

Share Improve this question asked May 24, 2017 at 18:53 kravekrave 1,9196 gold badges22 silver badges42 bronze badges 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 – Nijikokun Commented May 24, 2017 at 18:55
  • What's "array data" if not JSON? CSV? – Bergi Commented May 24, 2017 at 18:55
  • confused What specifically is the API sending back? Not JSON? – Dave Newton Commented May 24, 2017 at 18:56
  • Won't you just need to parse the JSON? – Natu Myers 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. – Bergi Commented May 24, 2017 at 18:57
 |  Show 1 more ment

1 Answer 1

Reset to default 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 pletely dependent on how your API is encoding it and I cannot answer that without more detail regarding your API response.

本文标签: javascriptHow to use fetch API to get an Array backStack Overflow