2015-05-11 110 views
0

我有这样的HTML箱:无法解析JSON JavaScript对象

<span>Select depatament</span><span> 
    <select id="department" onchange="EnableSlaveSelectBox(this)" data-slaveelaments='{"a": 1, "b": "2"}'> 
     <option selected disabled>-Select-</option> 
    </select> 
</span> 

事件的onchange()实现:

function EnableSlaveSelectBox(element) { 
    var d = $('#department').data('slaveelaments'); 
    alert($.parseJSON(d)); 
} 

但当的onchange()事件被激发我就在这排:

alert($.parseJSON(d)); 

此错误:

SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符 return JSON.parse(data +“”);

任何想法为什么我上面的错误? 预先感谢您。

回答

1

你的情况,你不需要使用parseJSON,因为dObject

function EnableSlaveSelectBox(element) { 
    var d = $('#department').data('slaveelaments'); 

    console.log(d.a); 
    console.log(d.b); 
} 

Example

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.

$.data

3

因为,有趣的是,jQuery的似乎自动解析字符串到一个对象。除了

alert(JSON.stringify(d)); // {"a":1,"b":"2"} 

:为了验证这一点:

alert(d); // [object Object] 

还是这样做是为了再次看到字符串化版本,我不知道的jQuery这样做,直到我测试了它。

+0

我正要张贴同样的事情。 。 。你每天学习新的东西。 :)很好的功能jQuery的家伙! – talemyn

2

jQuery data()已经将格式正确的json转换为数组或对象。

这也会在API的文档

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.

data() API DOCS