ZeroChow
ZeroChow

Reputation: 442

Fetch API get raw value from Response

I use React-Native request some data, here is my code:

    fetch('https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json')
      .then((response)=>{
        return response.json()
      })
      .then((responseJSON)=>{
        callback(responseJSON)
      })
      .catch((error)=>{
        console.error(error);
      })
      .done()

I see the response is a Response object, and the json function code is return this.text().then(JSON.parse), I'm confused that what is the parameter of theJSON.parse? Is that the response raw value? How can I get it?

Upvotes: 14

Views: 29896

Answers (1)

AndrewL
AndrewL

Reputation: 3470

Here's how you'd do what you want. In my case I wanted to manually parse the JSON because a certain character (\u001e) is improperly parsed by the in-built JSON parser.

Change from:

fetch(url)
    .then(response => response.json()) 
    .then((data) => {
        data....

to:

fetch(url)
    .then(response => response.text()) 
    .then((dataStr) => {
        let data = JSON.parse(dataStr);
        data...

Upvotes: 18

Related Questions