django escapejs和simplejson [英] django escapejs and simplejson

查看:330
本文介绍了django escapejs和simplejson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用simplejson.dumps将Python数组编码为json:

 在[30]中:s1 = ['test','< script>'] 

在[31]中:simplejson.dumps(s1)
输出[31]:'[test,< script> ;''

工作正常。



但是我想在调用simplejson.dumps之前首先转义字符串(使用Django中的escapejs):

 在[35]中: s_esc 
输出[35]:[u'test',u'\\\\']

在[36]中:print simplejson.dumps(s_esc)
[test,\\]

我的问题是:我想要转义的字符串是: [test,\\\] 而不是 [测试,\\\\]



我可以使用替换

 在[37]中:print simplejson.dumps(s_esc).replace('\\ \\, '\\')
[test,\\\]


$ b $这是一个好办法吗?我只想在将它们编码为json之前先排除字符串。所以当我在模板中使用它们时,就没有语法错误。



谢谢。 :)

解决方案

simplejson 2.1.0及更高版本包含一个 JSONEncoderForHTML 编码器,完全符合您的要求。在您的示例中使用它:

 >>> s1 = ['test','< script>'] 
>>> simplejson.dumps(s1,cls = simplejson.encoder.JSONEncoderForHTML)
'[test,\\]'
/ pre>

最近遇到这个问题,我没有控制生成数据结构的代码,所以我不能像以前那样逃避字符串正在组装。 JSONEncoderForHTML在输出点整齐地解决了这个问题。



当然,你需要有simplejson 2.1.0或更高版本。 (Django曾经使用旧版本,Django 1.5完全不推荐使用django.utils.simplejson)如果由于某种原因您无法升级, JSONEncoderForHTML代码相对较小,可能会被拉入较早的代码或与 Python 2.6 +的json包 - 虽然我还没有尝试过这个


I'm trying to encode a Python array into json using simplejson.dumps:

In [30]: s1 = ['test', '<script>']

In [31]: simplejson.dumps(s1)
Out[31]: '["test", "<script>"]'

Works fine.

But I want to escape the strings first (using escapejs from Django) before calling simplejson.dumps:

In [35]: s_esc
Out[35]: [u'test', u'\\u003Cscript\\u003E']

In [36]: print simplejson.dumps(s_esc)
["test", "\\u003Cscript\\u003E"]

My problem is: I want the escaped string to be: ["test", "\u003Cscript\u003E"] instead of ["test", "\\u003Cscript\\u003E"]

I can use replace:

In [37]: print simplejson.dumps(s_esc).replace('\\\\', '\\')
["test", "\u003Cscript\u003E"]

But is this a good approach? I just want to escape the strings first before encoding them to json. So there will be no syntax errors when I use them in template.

Thanks. :)

解决方案

simplejson 2.1.0 and later include a JSONEncoderForHTML encoder that does exactly what you want. To use it in your example:

>>> s1 = ['test', '<script>']
>>> simplejson.dumps(s1, cls=simplejson.encoder.JSONEncoderForHTML)
'["test", "\\u003cscript\\u003e"]'

I ran into this recently where I didn't have control over the code that was generating the data structures, so I couldn't escape the strings as they were being assembled. JSONEncoderForHTML solved the problem neatly at the point of output.

Of course, you'll need to have simplejson 2.1.0 or later. (Django used to come with an older version, and Django 1.5 deprecated django.utils.simplejson entirely.) If you can't upgrade for some reason, the JSONEncoderForHTML code is relatively small and could probably be pulled into earlier code or used with Python 2.6+'s json package -- though I haven't tried this myself

这篇关于django escapejs和simplejson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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