【发布时间】: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