[Answered ]-Encoding JSON with strings in html data attributes

2👍

Despite the fact it is a bit hacky to store json in attribute, single-quotation (apostrophe , U+0027) is not a valid string delimiter in JSON. Some browsers may have problems with this, although I cannot point out any.

If the JSON struct is not complex store every field as a separate data-*, otherwise in JS.

If you need to use attribute… really, really …I would not replace quotes (simple replace will be loosy) more likely encode it with base64.

Note about escaping: To escape double-quotes (single as well) you can use filter addslashes (or in python django.template.defaultfilters.addslashes), but it is not json data aware so it may break.

Leave a comment