我正在尝试通过jQuery解析通过AJAX从远程服务器获取的JSON数据。JSON数据如下:{identifier:"ID", label:"LABEL"}
,但无法解析。显然,标识符和标签字段没有双引号。在我的本地测试网站上使用双引号进行测试时可以正常工作。
是否可以在不使用引号的情况下通过jQuery使其正常工作?我已经搜索了很多,但没有找到解决方案。
感谢您的任何输入。
我正在尝试通过jQuery解析通过AJAX从远程服务器获取的JSON数据。JSON数据如下:{identifier:"ID", label:"LABEL"}
,但无法解析。显然,标识符和标签字段没有双引号。在我的本地测试网站上使用双引号进行测试时可以正常工作。
是否可以在不使用引号的情况下通过jQuery使其正常工作?我已经搜索了很多,但没有找到解决方案。
感谢您的任何输入。
是的,它不是有效的JSON格式,但是谁在乎它是否有效。
至少我不在乎,我只想解析它,所以我写了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规范如下:
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.
将字符串视为你提到的标签。
通过使用正则表达式,可以将无效的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);