gpt4 book ai didi

javascript - 带有双引号的数据属性的 jQuery JSON 解析失败

转载 作者:行者123 更新时间:2023-11-29 14:53:38 26 4
gpt4 key购买 nike

我发现在 jQuery 读取属性值时未正确获取 HTML 编码值(引号已解码),因此 JSON 解析因该值而失败。

这是 jQuery 中的错误还是我没有正确编码我的值?

这是我的 HTML 编码的 JSON 字符串:

[
{
"id": "1",
"organisation_id": "1",
"badge_id": "49",
"target": "15",
"target_type": "actions",
"target_title": null,
"target_description": null,
"start": "2014-01-15",
"name": "Our goal",
"description": "Vestibulum id ligula porta felis euismod semper. "Nullam" id dolor id nibh ultricies vehicula ut id elit. Nulla vitae elit libero, a pharetra augue. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.",
"created": "2013-08-07 14:26:56"
},
{
"id": "19",
"organisation_id": "1",
"badge_id": "49",
"target": "30000000",
"target_type": "numeric",
"target_title": "Revenue contribution",
"target_description": "Specify how much this action contributes to the revenue goal",
"start": "2014-01-21",
"name": "November revenue",
"description": "Reach revenue of $30,000,000 in November. Let's do this.",
"created": "2014-01-21 16:59:25"
}
]

请注意 description 属性中的 "

这里是问题的重现:http://jsfiddle.net/J8Xv6/

我认为这是一个出现在较新版本的 jQuery 中的问题。刚刚从 1.7.x 更新到 1.11.0。

最佳答案

这是无效的 JSON。当字符串进入 JavaScript 时,该 HTML 实体将变成双引号字符。字符串中的双引号字符必须用反斜杠转义。

字符的 HTML 编码使 HTML 解析器满意,但它会导致属性值在 JSON 值(字符串常量)中间有一个普通的双引号字符。

如果您在 HTML 实体前放置一个反斜杠,它将是有效的 JSON。

编辑 — 在您的 jsfiddle 中,您尝试使用 jQuery .data() 方法获取数据属性。这很好,但请注意,当 jQuery 看到看起来像 JSON 的内容时,它会尝试为您解析它。因此,当您取回属性值时,它已经被解析了。

关于javascript - 带有双引号的数据属性的 jQuery JSON 解析失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21555578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com