javascript - 将从元素的数据属性获得的字符串转换为json

标签 javascript jquery html json

我收到以下代码的错误。我知道 $.parseJSON() 对单引号/双引号敏感。我想不出解决这个问题的方法。你能帮忙吗?

<div data-x='{"a":"1","b":"2"}'></div>

$(document).ready(function(){
    var data =$.parseJSON($("div").data("x"))
    alert(data.a)
})

https://jsfiddle.net/r2Lnfbpm/

最佳答案

jQuery的data()做的是类型转换,所以当data属性是有效的JSON时,它已经被解析成一个对象,将一个对象传递给$.parseJSON产生一个错误,因为它需要一个 JSON 字符串。

$(document).ready(function(){
    var data = $("div").data("x");
    console.log(data.a);
});

来自documentation

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).
A value is only converted to a number if doing so doesn't change the value's representation.

For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

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.

To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

关于javascript - 将从元素的数据属性获得的字符串转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996081/

相关文章:

javascript - 使用html5的跨平台游戏开发

javascript - 我正在尝试抓取一些数据并将其导出到 CSV

html - 改变按钮的大小

javascript - 查询/JavaScript : Countdown Timer acting erratically

jquery - 导航下的滑动条 jQuery CSS

javascript - 使用 Javascript 显示/隐藏表格行

javascript - 使用 addEventListener 附加时不调用事件

javascript - 我怎样才能减少字符数

javascript - 如何使用 Dojo 重现此 JQuery ajax

javascript - 使用 JavaScript 的 Sticky Nav 问题