如何解析格式不正确的JSON(也许使用jQuery) [英] How can you parse NON wellformed JSON (maybe using jQuery)
问题描述
除了使用eval
之外,还有没有其他方法可以解析格式不正确的JSON?
Is there a way to parse NON wellformed JSON, other than using eval
?
背景是,我正在使用数据标签值绘制这样的图形:
The background is, that I'm using data tag values to draw a graph like this:
<div id="data" data-idata="[1,2,3]" data-sdata="['foo','bar','baz']"></div>
这完美地适用于数值,这些值直接作为数组传递到jQuery数据中,无需在此处解析JSON.
This works flawlessly with numeric values, these values are delivered as an array directly in jQuery data, no need to parse JSON here.
但是,对于标签,将传递字符串数组. eval
可以很好地解析sdata
中的字符串,但是JSON.parse
和jQuery.parseJSON
失败,因为它的格式不正确的JSON.
However, for the labels a string array is to be passed. eval
can parse the string in sdata
just fine, but JSON.parse
and jQuery.parseJSON
fail, because it's not wellformed JSON.
var $data = $("#data").data(),
values;
// use eval
out("#out", eval($data.sdata)); // works...
// use JSON.parse
try
{
values = JSON.parse($data.sdata);
} catch(e) {
// silent catch
}
out("#out1", values); // values is undefined
我在这里整理了 JsFiddle 来检查问题.
I put together a JsFiddle here to check the thing.
推荐答案
由于['foo','bar','baz']
包含单引号引起了错误. JSON RFC 指定string
应该用双引号标记.
You get error because ['foo','bar','baz']
contains single-quotation marks. JSON RFC specifies that string
should be enclosed in double-quotation marks.
可能有一些解决方法.
There could be a few work-arounds.
在data-
属性中切换引号:
<tag data-sdata='["foo","bar","baz"]' />
或替换为Javascript
Or replace in Javascript:
values = JSON.parse($data.sdata.replace("'","\""));
这篇关于如何解析格式不正确的JSON(也许使用jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!