javascript - 我如何 JSON.parse 来自 URL 的字符串(React Native)

标签 javascript json string react-native fetch

我有一个带有字符串的 URL,我想对其进行 JSON.parse (我是 React Native 的新手)。

这是带有字符串的 URL 的一部分 -

<string>[{"Song_ID":"11","Song_Name":"The Doors - People","Song_File":"http://myurl.com/songs/The_Doors_People.mp3","Image":"http://myurl.com/images/The_Doors.jpg"},{"Song_ID":"12","Song_Name":"Smashing Pumpkins - Porcelina","Song_File":"http://myurl.com/songs/Smashing_Pumpkins_Porcelina.mp3","Image":"http://myurl.com/images/Mellon_Collie.jpg"},]</string>

这是代码,我相信 fetch 有问题。 dataSource: JSON.parse(responseJson) 无法完成这项工作。

const URL =
  "http://mobile.domain.com/site/WebService.asmx/SongsList";


export default class FetchExample extends React.Component {
  static navigationOptions = {
    title: "Json Data"
  };
  constructor(props) {
    super(props);
    this.state = { isLoading: true };
  }

  componentDidMount() {
    return fetch(URL)
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: JSON.parse(responseJson) // doesn't work
          },
          function() {}
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

我尝试了 dataSource: JSON.stringify(responseJson) 但它也没有完成这项工作。 渲染代码 -(我希望这部分没问题 - data={this.state.dataSource})

   render(){

    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.Song_ID}, {item.Song_Name}</Text>}
          keyExtractor={({id}, index) => id} // this part with the "id" and "index" I dont understand (the index in my code is fade)
        />
      </View>
    );
  }
}

它向我显示错误:“JSON 解析错误:无法识别的标记‘<’”。

最佳答案

it shows me the error: " JSON Parse error: Unrecognized token '<' ".

这意味着您要解析的不是 JSON。因此,您需要使用浏览器的网络选项卡来查看它是什么。

如果这确实是您问题中的内容:

[{"Song_ID":"11","Song_Name":"The Doors - People","Song_File":"http://myurl.com/songs/The_Doors_People.mp3","Image":"http://myurl.com/images/The_Doors.jpg"},{"Song_ID":"12","Song_Name":"Smashing Pumpkins - Porcelina","Song_File":"http://myurl.com/songs/Smashing_Pumpkins_Porcelina.mp3","Image":"http://myurl.com/images/Mellon_Collie.jpg"},]

Then there are two problems with it:

  1. The <string> at the start and the </string> at the end (and that fits your error message), and

  2. In JSON, you can't have a trailing comma in an array.

Here's the correct JSON version of that:

[{"Song_ID":"11","Song_Name":"The Doors - People","Song_File":"http://myurl.com/songs/The_Doors_People.mp3","Image":"http://myurl.com/images/The_Doors.jpg"},{"Song_ID":"12","Song_Name":"Smashing Pumpkins - Porcelina","Song_File":"http://myurl.com/songs/Smashing_Pumpkins_Porcelina.mp3","Image":"http://myurl.com/images/Mellon_Collie.jpg"}]

Another possibility is that you're not getting the JSON you think you are at all, and instead it's an error message from the server as HTML (given that < character). (The HTML may well be reporting an error, see #4 below.)

But you have two other problems:

  1. You're trying to double-parse the JSON:

    componentDidMount() {
      return fetch(URL)
        .then(response => response.json()) // <=== Parses the JSON
        .then(responseJson => {
          this.setState(
            {
              isLoading: false,
              dataSource: JSON.parse(responseJson) // <=== Tries to parse it again
            },
            function() {}
          );
        })
        .catch(error => {
          console.error(error);
        });
    }
    

    只解析一次。

  2. 您的代码需要检查 response.ok。你不是唯一一个错过这张支票的人,人们错过它是如此普遍,我 wrote it up on my anemic little blog .

所以(见***评论):

componentDidMount() {
  return fetch(URL)
    .then(response => {
        if (!response.ok) {                      // *** Check errors
            throw new Error(                     // ***
                "HTTP status " + response.status // ***
            );                                   // ***
        }                                        // ***
        return response.json();                  // *** Parse the JSON (once)
    })
    .then(dataSource => {                        // *** More accurate name
      this.setState(
        {
          isLoading: false,
          dataSource                             // *** Use the parsed data
        },
        function() {}
      );
    })
    .catch(error => {
      console.error(error);
    });
}

在您的评论中:

I can't remove the tag , it comes from c# url WebService.asmx

您应该能够在 WebService.asmx 中修复该问题。 ASP.net 绝对可以生成有效的 JSON。否则,你不能直接将其解析为 JSON。

但是 - 我推荐这样做 - 如果绝对必要,您可以预处理字符串以处理我指出的两个问题:

componentDidMount() {
  return fetch(URL)
    .then(response => {
        if (!response.ok) {                      // *** Check errors
            throw new Error(                     // ***
                "HTTP status " + response.status // ***
            );                                   // ***
        }                                        // ***
        return response.text();                  // *** Read the TEXT of the response
    })
    .then(dataSourceText => {                    // *** More accurate name
      // *** Remove the invalid parts and parse it
      const dataSource = JSON.parse(
        dataSourceText.match(/^<string>(.*),]<\/string>$/)[1] + "]"
      );
      this.setState(
        {
          isLoading: false,
          dataSource                             // *** Use the parsed data
        },
        function() {}
      );
    })
    .catch(error => {
      console.error(error);
    });
}

关于javascript - 我如何 JSON.parse 来自 URL 的字符串(React Native),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069002/

相关文章:

Char 数组不会作为字符串打印到控制台

javascript - 用javascript中的对象替代 'self = this'

javascript - 区域.js : Uncaught RangeError: Maximum call stack size exceeded

javascript - 访问数组中的 JSON 对象

Python JSON 数据选择

javascript - 如何使用 javascript 使用来自 asp.net webservice 的 Json 数据

javascript - 如何从返回的 JSON 字符串中提取某些数据?

string - 从源和结果字符串中查找加密算法

javascript - d3 使用按钮缩放并双击但不要使用滚轮缩放

javascript - 使用 javascript 调用元素内的部分 View