简体   繁体   English

无法将 JSON 解析为 Javascript 对象

[英]Can't parse JSON to Javascript object

I have this HTML box:我有这个 HTML 框:

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

Event onchange() implementation:事件 onchange() 实现:

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

But when onchange() event is fired I get on this row:但是当 onchange() 事件被触发时,我得到了这一行:

alert($.parseJSON(d));

This error:这个错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data SyntaxError: JSON.parse: JSON 数据第 1 行第 2 列的意外字符

return JSON.parse( data + "" );返回 JSON.parse( 数据 + "" );

Any idea why I get error above?知道为什么我会收到上面的错误吗?

Because, interestingly, jQuery seems to automatically parse the string to an object.因为,有趣的是,jQuery 似乎会自动将字符串解析为对象。 To test this:要测试这个:

alert(d); // [object Object]

Or do this to see the stringified version again:或者执行此操作以再次查看字符串化版本:

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

Aside: I didn't know jQuery did that until I tested it.旁白:在我测试之前,我不知道 jQuery 这样做了。

jQuery data() will already convert properly formatted json to array or object. jQuery data() 已经将格式正确的 json 转换为数组或对象。

This is as documented in APi这是在 APi 中记录的

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string;当数据属性是一个对象(以'{'开头)或数组(以'['开头)时,则使用jQuery.parseJSON来解析字符串; it must follow valid JSON syntax including quoted property names.它必须遵循有效的 JSON 语法,包括带引号的属性名称。 If the value isn't parseable as a JavaScript value, it is left as a string.如果该值无法解析为 JavaScript 值,则将其保留为字符串。

data() API DOCS数据()API文档

In your case you don't need use parseJSON , because d is Object ,在您的情况下,您不需要使用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;当数据属性是一个对象(以'{'开头)或数组(以'['开头)时,则使用jQuery.parseJSON来解析字符串; it must follow valid JSON syntax including quoted property names.它必须遵循有效的 JSON 语法,包括带引号的属性名称。 If the value isn't parseable as a JavaScript value, it is left as a string.如果该值无法解析为 JavaScript 值,则将其保留为字符串。

$.data $.data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM