Reputation: 24768
I have json inside a data attribute. It's valid in online validators like http://jsonlint.com/. Still it trows an error. What is wrong?
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);
});
Fiddle
https://jsfiddle.net/q89hph0L/
Uncaught SyntaxError: Unexpected token '
UPDATE:
It seems to work if copy paste the json into a string and parse it. Updated fiddle: https://jsfiddle.net/q89hph0L/4/
So, it cannot have json as data attribute?
Upvotes: 1
Views: 498
Reputation: 96889
"
gets rendered by browser into "
, see: How to escape double quotes in title attribute. It's the same usecase as yours.
Solution is to replace "
with \"
and when using jQuery.data
you don't even have to parse the string with JSON.parse()
. Updated jsfiddle: https://jsfiddle.net/0qryjrya/.
Upvotes: 3