处理json数据时出错:由于数据格式不正确,因此无法读取 [英] error processing json data: The data couldn’t be read because it isn’t in the correct format
问题描述
这个错误整个上午都很烦人,我正在尝试以以下格式检索JSON:
This error has been annoying all morning, I'm trying to retrieve JSON in the format:
song = {
'artist':'Tom Waits',
'song':'New Coat Of Paint',
'lyrics':'Let\'s put a new coat of paint on this lonesome old town\nSet \'em up, we\'ll be knockin\' em [...]',
'url':'http://lyrics.wikia.com/Tom_Waits:New_Coat_Of_Paint'
}
从以下网址
: JSON URL
这是我用来解析数据的函数:
This is the function I'm using to parse the data:
func parseJSONFromData(_ jsonData: Data?) -> [String : AnyObject]?
{
if let data = jsonData {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : AnyObject]//Parses data into a dictionary
return jsonDictionary
} catch let error as NSError {
print("error processing json data: \(error.localizedDescription)")
}
}
return nil
}
}
推荐答案
如果您访问网站 http://json.parser.online.fr ,它将使您粘贴数据并检查其是否为有效JSON.你不是.
If you go to the site http://json.parser.online.fr it will let you paste in data and check to see if it's valid JSON or not. Yours is not.
正如其他人所说,字符串需要用双引号而不是单引号引起来,并且"="无效.
As others have said, strings need to be enclosed in double quotes, not single quotes, and the "=" is not valid.
编写用"
替换所有出现的'
的代码非常容易. song =
位不太清楚. JSON的正确格式为:
It would be quite easy to write code that would replace all occurrences of '
with "
. The song =
bit is less clear. The correct format for JSON would be:
{
"song": {
"artist":"Tom Waits",
"song":"New Coat Of Paint",
"lyrics":"Let\"s put a new coat of paint on this lonesome old town\nSet \"em up, we\"ll be knockin\" em [...]",
"url":"http://lyrics.wikia.com/Tom_Waits:New_Coat_Of_Paint"
}
}
或者您可以完全摆脱外部词典:
Or you could get rid of the outer dictionary entirely:
{
"artist":"Tom Waits",
"song":"New Coat Of Paint",
"lyrics":"Let\"s put a new coat of paint on this lonesome old town\nSet \"em up, we\"ll be knockin\" em [...]",
"url":"http://lyrics.wikia.com/Tom_Waits:New_Coat_Of_Paint"
}
您需要查看您的数据,并弄清楚在什么情况下它是不合法的JSON,这是怎么回事.
You need to look at your data and figure out what's wrong with it in the general case that makes it not legal JSON.
进一步挖掘之后,似乎您所使用的URL返回的是JavaScript,而不是JSON.试试这样的网址:
After further digging, it seems that the URLs you're using are returning JavaScript, not JSON. Try an URL like this instead:
这应该为您提供格式正确的JSON的Tom Waits歌曲New Coat of Paint的歌词.
That should give you the lyrics of the Tom Waits song New Coat of Paint in well-formed JSON.
此Github页面提供有关可用于查询该网站并获取歌词的搜索参数的信息:
This Github page gives info on the search parameters you can use to query that site and get lyrics:
这篇关于处理json数据时出错:由于数据格式不正确,因此无法读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!