我在数据属性中有json。它在http://jsonlint.com/等在线验证器中有效。它仍然存在错误。有什么问题?
HTML
<div class="seo" data-seo-controller='{"values":{"child_count":"0","type":"tables"},"title":{"field":"\u00e5\u00e4\u00f6 llasdas","template":"This page has {{child_count}} {{type}}!","prefix":"","suffix":" - Products","fallback":"\u00e5\u00e4\u00f6 llasdas","full":"\u00e5\u00e4\u00f6 llasdas - Products","full-replaced":"\u00e5\u00e4\u00f6 llasdas - Products"},"description":{"field":"rwerwe wer " ' ewrerte fsd :'","fallback":"rwerwe wer " ' ewrerte fsd :'","full":"rwerwe wer " ' ewrerte fsd :'","full-replaced":"rwerwe wer " ' ewrerte fsd :'","template":"","prefix":"","suffix":"","limit":155},"url":{"edit":"http:\/\/localhost\/seo\/panel\/pages\/saved-value\/url","preview":"seo\/saved-value"}}'>
的jQuery
$( document ).ready(function() {
var json = $('.seo').attr('data-seo-controller');
controller = jQuery.parseJSON( json );
console.log(controller);
});
小提琴
https://jsfiddle.net/q89hph0L/
Uncaught SyntaxError:意外的令牌&#39;
更新
如果复制将json粘贴到字符串中并解析它,似乎有效。更新了小提琴:https://jsfiddle.net/q89hph0L/4/
那么,它不能将json作为数据属性吗?
答案 0 :(得分:2)
"
由浏览器呈现为"
,请参阅:How to escape double quotes in title attribute。它与您的用例相同。
解决方案是将"
替换为\"
,使用jQuery.data
时,您甚至不必使用JSON.parse()
解析字符串。更新了jsfiddle:https://jsfiddle.net/0qryjrya/。