jQuery JSON parsing fails for data attribute with double quotes jQuery JSON parsing fails for data attribute with double quotes json json

jQuery JSON parsing fails for data attribute with double quotes


That's invalid JSON. By the time the string makes it to JavaScript, that HTML entity will have become a double-quote character. Double-quote characters in strings must be escaped with a backslash.

The HTML-encoding of the character makes the HTML parser happy, but it results in an attribute value that's got a plain double-quote character in the middle of the JSON value (string constant).

If you put a backslash before the HTML entity, it'll be valid JSON.

edit — in your jsfiddle, you're attempting to fetch the data attribute with the jQuery .data() method. That's fine, but be aware that when jQuery sees stuff that looks like JSON, it will try to parse it for you. Thus when you get back the attribute value it'll already be parsed.


Your attribute taking the data this way,

"[{"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"}]"

The error will be raises bold word , double quotes contains inside double quotes.

"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."