简体   繁体   中英

Encoding JSON with strings in html data attributes

I need to pass some data to javascript. So I've created a template tag :

from django.utils.safestring import mark_safe
from django import template
import json

register = template.Library()

@register.simple_tag
def mydata():
    return mark_safe(json.dumps([("a", 1), ("b", 2)])

Then in my template,

<div id="mydata" data-stuff="{% mydata %}" style="display:none;"></div>

Which is used in a js file with jquery loaded:

$('#mydata').data('stuff') //automatically does JSON.parse

The problem is the quotes from "a" and "b" break the HTML attribute syntax. I can simply change to single quotes ( data-stuff='{% mydata %}' ) but is there a more definitive django approach to injecting JSON into the template? Perhaps something like an escape_my_json or escape_for_html_attribute function.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM