我收到以下代码的错误。我知道 $.parseJSON()
对单引号/双引号敏感。我想不出解决这个问题的方法。你能帮忙吗?
<div data-x='{"a":"1","b":"2"}'></div>
$(document).ready(function(){
var data =$.parseJSON($("div").data("x"))
alert(data.a)
})
最佳答案
jQuery的data()
做的是类型转换,所以当data属性是有效的JSON时,它已经被解析成一个对象,将一个对象传递给$.parseJSON
产生一个错误,因为它需要一个 JSON 字符串。
$(document).ready(function(){
var data = $("div").data("x");
console.log(data.a);
});
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/