Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping/encoding single quotes in JSON encoded HTML5 data attributes

In PHP, I use json_encode() to echo arrays in HTML5 data attributes. As JSON requires - and json_encode() generates - values encapsulated by double quotes. I therefor wrap my data attributes with single quotes, like:

<article data-tags='["html5","jquery","php","test's"]'> 

As you can see, the last tag (test's) contains a single quote, and using json_encode() with no options leads to parsing problems.

So I use json_encode() with the JSON_HEX_APOS parameter, and parsing is fine, as my single quotes are encoded, but I wonder: is there a downside doing it like this?

like image 659
Jérémy F. Avatar asked Jan 12 '12 09:01

Jérémy F.


People also ask

How do you escape a single quote in JSON?

In JSON, you don't need to escape single quotes inside a value that is enclosed with double-quotes. In the case that you have double quotes as part of a value (that is enclosed with double quotes) then you would need to escape them.

Can you use single quotes in JSON?

Does JSON work with single quotes? Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .


1 Answers

You need to HTML escape data echoed into HTML:

printf('<article data-tags="%s">',     htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8')); 
like image 131
deceze Avatar answered Oct 02 '22 13:10

deceze