如何让python json.dumps()转义正斜杠?

时间:2018-06-07 05:51:51

标签: python json escaping

在我的JSON文件中,我有带正斜杠的字符串,似乎是转义的。例如。 This is path: \/home\/user\/test.txt。当我使用Python的内置json.loads()方法导入它时,将删除转义斜杠。

评论herehere正确地指出,在JSON中\/基本上与/意味着相同,所以这是可以预期的。

问题是,当我稍后再次通过json.dumps()导出JSON数据时,我希望这些正斜杠保持转义。我正在使用的JSON文件应尽可能保持不变。

在执行所需的数据操作后,我在编写JSON时遇到了一个hack:json_str.replace('/', '\/')。这对我来说很难看,还是我弄错了?还有更好的办法吗?

这是一个更完整的例子:

$ python
Python 2.7.13 (default, Nov 24 2017, 17:33:09) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> import collections
>>> a = r"""{
...     "version": 1,
...     "query": "This is path: \/home\/user\/test.txt"
... }"""
>>> j = json.loads(a, object_pairs_hook=collections.OrderedDict)
>>> print j
OrderedDict([(u'version', 1), (u'query', u'This is path: /home/user/test.txt')])
>>> print json.dumps(j, indent=4, separators=(',', ': '))
{
    "version": 1,
    "query": "This is path: /home/user/test.txt"
}
>>> print json.dumps(j, indent=4, separators=(',', ': ')).replace('/', '\/')
{
    "version": 1,
    "query": "This is path: \/home\/user\/test.txt"
}
>>> 

0 个答案:

没有答案
相关问题