使用jQuery解析没有引号的JSON数据
我正在尝试使用jQuery解析JSON,我通过AJAX从远程服务器获取。 JSON数据类似于: {identifier:"ID", label:"LABEL"}
但无法执行。 显然,字段标识符和标签没有双引号。 它在我的本地测试站点上使用双引号进行测试时有效。
是否可以在没有jQuery引号的情况下工作? 我四处寻找并找不到解决方案。
任何输入都表示赞赏。 谢谢。
你不能。 JSON规范说:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
意思是字符串作为你提到的标签。
资料来源: http : //www.json.org/
是的,它不是有效的JSON,blahblahblah …就像每个人都在乎它是否有效。
至少我不在乎,我只是想解析它,所以我写了jsonlite。
与Jsonlite ,你可以这样做:
var s = '{name: jsonlite, birthday: {year: 2013, month: 7, day: 7}, isGreat: true}'; var obj = jsonlite.parse(s);
其结果与下面的代码完全相同:
var s = '{"name": "jsonlite", "birthday": {"year": 2013, "month": 7, "day": 7}, "isGreat": true}'; var obj = $.parseJSON(s);
使用正则表达式,可以使无效的JSON成为有效的JSON。 在下面的示例中,sFixed将是有效的JSON,可以解析:。
let s = '{identifier:"ID", label:"LABEL"}', sFixed = s.replace(/(['"])?([a-zA-Z0-9_][a-zA-Z0-9_\s]*[a-zA-Z0-9_])(['"])?:/g, '"$2": '), //'{"identifier":"ID", "label":"LABEL"}' obj = JSON.parse(sFixed);