JSON内的HTML标签(在Python中) [英] HTML tags within JSON (in Python)

查看:535
本文介绍了JSON内的HTML标签(在Python中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解它不是一个理想的情况,但是如果我需要在JSON标签中有某种HTML,例如:

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

这是可能在Python中做的,而不需要预先逃脱吗?



它最初将是一个字符串,所以我正在考虑编写一个正则表达式,尝试在处理之前进行匹配和转义,但我只想确保有

解决方案

嗯,根据HTML的多样性,你可以使用HTML中的单引号,所以你可以这样做:

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

但是,使用 simplejson ,它作为 json模块构建到Python 2.6中,它自动执行任何转义:

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


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.

解决方案

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>"}}'

这篇关于JSON内的HTML标签(在Python中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆