[英]error processing json data: The data couldn’t be read because it isn’t in the correct format
這個錯誤整個上午都很煩人,我正在嘗試以以下格式檢索JSON:
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'
}
來自此URL: JSON URL
這是我用來解析數據的函數:
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。 你的不是。
正如其他人所說,字符串需要用雙引號而不是單引號引起來,並且“ =”無效。
這將是很容易編寫的代碼,將取代所有出現的'
有"
。該song =
。有點不太清楚的JSON正確的格式是:
{
"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"
}
}
或者您可以完全擺脫外部詞典:
{
"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返回的是JavaScript,而不是JSON。 試試這樣的URL:
那應該以格式正確的JSON為您提供Tom Waits歌曲New Paint of Paint的歌詞。
這個Github頁面提供有關搜索參數的信息,您可以使用這些參數來查詢該站點並獲取歌詞:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.