Jens Törnell
Jens Törnell

Reputation: 24768

jQuery parse json error in valid json

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 &quot; &#039; ewrerte fsd :&#039;","fallback":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","full":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","full-replaced":"rwerwe wer &quot; &#039; ewrerte fsd :&#039;","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

Answers (1)

martin
martin

Reputation: 96889

&quot; 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 &quot; 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

Related Questions