[英]How do I JSON.parse a string from URL (React Native)
I have a URL with a string which I want to JSON.parse it (I'm new at React native). 我有一个URL,其中包含一个我想进行JSON解析的字符串(我是React native的新手)。
here is part of the URL with the string - 这是带有字符串的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>
Here is the code, I believe the fetch has the problem. 这是代码,我相信提取存在问题。 The dataSource: JSON.parse(responseJson)
doesn't do the job. 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); }); }
I tried dataSource: JSON.stringify(responseJson)
but it doesn't do the job also. 我尝试了dataSource: JSON.stringify(responseJson)
但它也没有做这项工作。 The render code - (I hope this part is ok - data={this.state.dataSource}
) 渲染代码-(我希望这部分工作正常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> ); } }
it shows me the error: " JSON Parse error: Unrecognized token '<' ". 它向我显示错误:“ JSON解析错误:无法识别的令牌'<'”。
it shows me the error: " JSON Parse error: Unrecognized token '<' ". 它向我显示错误:“ JSON解析错误:无法识别的令牌'<'”。
That means what you're trying to parse isn't JSON. 这意味着您要解析的不是JSON。 So you'll want to use the browser's Network tab to see what it is. 因此,您将需要使用浏览器的“网络”选项卡查看其内容。
If it's really what you have in your question: 如果问题确实存在,请执行以下操作:
[{"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: 然后有两个问题:
The <string>
at the start and the </string>
at the end (and that fits your error message), and 所述<string>
在开始和</string>
末(和适合你的错误消息),和
In JSON, you can't have a trailing comma in an array. 在JSON中,数组中不能包含结尾逗号。
Here's the correct JSON version of that: 这是正确的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"}]
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). 另一种可能性是,您根本没有得到自己认为的JSON,而是从服务器以HTML形式返回错误消息(给定<
字符)。 (The HTML may well be reporting an error, see #4 below.) (HTML很有可能报告错误,请参阅下面的#4。)
But you have two other problems: 但是您还有另外两个问题:
You're trying to double-parse the JSON: 您正在尝试双重解析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); }); }
Only parse it once. 仅解析一次。
Your code needs to check response.ok
. 您的代码需要检查response.ok
。 You're not alone in missing out this check, it's so common that people miss it out that I wrote it up on my anemic little blog . 您并不是唯一一个错过这张支票的人,它很常见,人们都错过了这张支票,以至于我在贫乏的小博客上写下了这张支票。
So (see ***
comments): 因此(请参阅***
评论):
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);
});
}
In a comment you've said: 在评论中,您说过:
I can't remove the tag , it comes from c# url WebService.asmx 我无法删除标签,它来自c#url WebService.asmx
You should be able to fix that in WebService.asmx. 您应该能够在WebService.asmx中对其进行修复。 ASP.net absolutely can produce valid JSON. ASP.net绝对可以产生有效的JSON。 Otherwise, you can't directly parse it as JSON. 否则,您将无法直接将其解析为JSON。
But — and I don't recommend this — if absolutely necessary, you can pre-process the string to deal with the two issues I pointed out with it: 但是-我不建议这样做 -如果绝对必要,您可以对字符串进行预处理以处理我指出的两个问题:
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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.