HTML tags within JSON (in Python)

这一生的挚爱 提交于 2019-12-23 22:26:00

问题


I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.:

{
    "node":
    {
        "list":"<ul><li class="lists">Hello World</li><ul>"
    }
}

is this possible to do in Python without requiring to to be escaped beforehand?

It will be a string initially so I was thinking about writing a regular expression to attempt to match and escape these prior to processing, but I just want to make sure there isn't an easier way.


回答1:


Well, depending on how varied your HTML is, you can use single quotes in HTML fine, so you could do:

{
    "node":
    {
        "list": "<ul><li class='lists'>Hello World</li><ul>"
    }
}

However, with simplejson, which is built into Python 2.6 as the json module, it does any escaping you need automatically:

>>> import simplejson
>>> simplejson.dumps({'node': {'list': '<ul><li class="lists">Hello World</li><ul>'}})
'{"node": {"list": "<ul><li class=\\"lists\\">Hello World</li><ul>"}}'



回答2:


You can have arbitrary strings there, including ones which happen to contain HTML tags (the only issue with your example is the inner " which would confuse any parser).



来源:https://stackoverflow.com/questions/963448/html-tags-within-json-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!