错误处理json数据:无法读取数据,因为它的格式不正确

时间:2017-05-13 17:52:37

标签: json swift parsing

这个错误整个上午都很烦人,我正在尝试以下列格式检索JSON:

df <- structure(list(Group = c("B", "A", "B", "A"), Salary = c(1000L, 
2000L, 3000L, 4000L)), .Names = c("Group", "Salary"),
class = "data.frame", row.names = c(NA, -4L))

来自此网址:JSON URL

这是我用来解析数据的函数:

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'
}

1 个答案:

答案 0 :(得分:1)

如果你去网站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。

编辑:

进一步挖掘后,您使用的网址似乎正在返回JavaScript,而不是JSON。请尝试使用这样的网址:

http://lyrics.wikia.com/wikia.php?controller=LyricsApi&method=getSong&artist=Tom%20Waits&song=new%20coat%20of%20paint

这应该会给你一个结构良好的JSON中Tom Waits歌曲New Coat of Paint的歌词。

此Github页面提供了可用于查询该网站并获取歌词的搜索参数的信息:

https://github.com/Wikia/app/blob/dev/extensions/wikia/LyricsApi/LyricsApiController.class.php#L10-L15