【问题标题】:How do I JSON.parse a string from URL (React Native)我如何 JSON.parse 来自 URL 的字符串(React Native)
【发布时间】:2019-04-03 18:31:58
【问题描述】:

我有一个带有字符串的 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 Parse error: Unrecognized token '

【问题讨论】:

  • 该错误意味着您尝试解析的 json 无效。您的数据一目了然有 2 个潜在问题 标签不是有效的 json,末尾的逗号也会导致验证失败。
  • 响应实际上是否包含“”标签?如果是这样,那是您的问题,您必须在使用 JSON.parse 之前将这些标签从字符串中解析出来
  • 还应该添加如果它已经是json,解析将失败。 JSON.parse 用于将字符串转换为 json。
  • 这个 .then(response => response.json()) .then(responseJson => { this.setState( { isLoading: false, dataSource: responseJson }, ); })`同样的错误
  • 见下面的答案。您没有从您的请求中获得有效的 JSON。我会检查网络选项卡,看看你得到什么响应。

标签: javascript json string react-native fetch


【解决方案1】:

它向我显示错误:“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 ","图片":"http://myurl.com/images/Mellon_Collie.jpg"},]

那么有两个问题:

  1. 开头的 &lt;string&gt; 和结尾的 &lt;/string&gt;(这符合您的错误消息),并且

  2. 在 JSON 中,数组中不能有尾随逗号。

这是正确的 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 ","图片":"http://myurl.com/images/Mellon_Collie.jpg"}]

另一种可能性是您根本没有得到您认为的 JSON,而是来自服务器的 HTML 错误消息(给定 &lt; 字符)。 (HTML 很可能会报告错误,请参见下面的 #4。)

但是你还有另外两个问题:

  1. 您正在尝试双重解析 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

所以(见*** cmets):

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

在你说过的评论中:

我无法删除标签,它来自 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);
    });
}

【讨论】:

  • 我复制了你的“componentDidMount() { return fetch(URL)”代码,在可视代码软件上出错,无法解决
  • @sup.DR - 这是一个简单的缺失)。我已经修好了。 (我还扩展了答案的开头。)但重点不是从答案中复制和粘贴代码,希望它能起作用。重点是了解代码在做什么,为什么,并将这些经验应用到您的代码中。
  • @sup.DR - 我在预处理字符串的末尾添加了一个示例,但实际上,这需要在服务器端修复。
  • 对不起,我仍然无法解决问题。我拿了这段代码 - 使用 StringBuilder - stackoverflow.com/questions/17398019/…。 (/^(.*),]$/)[1] + "]" 出错:null 不是对象
【解决方案2】:

似乎问题在于响应包含标签&lt;string&gt;&lt;/string&gt;。我认为如果你删除然后首先应该工作。

喜欢这个question

【讨论】:

  • “喜欢这个问题。” 如果您认为某个问题与另一个问题重复,请不要回答。相反,当你有足够的代表时,发表评论,然后当你有更多的代表时,投票关闭作为重复。在此之前,请耐心等待,系统采用这种方式设计是有原因的。
  • 我无法移除标签,它来自c# url WebService.asmx
  • @sup.DR - 你应该可以在 WebService.asmx 中修复它。 ASP.net 绝对可以生成有效的 JSON。否则无法直接解析为 JSON。
  • 我有这个 - 数据表到 Json Obj 代码 - stackoverflow.com/questions/17398019/… 它是这样来的(52 票)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 2012-09-27
相关资源
最近更新 更多