In my JSON file, I have strings with forward slashes that appear to be escaped. eg. This is path: \/home\/user\/test.txt
. When I import this using Python's built-in json.loads()
method, the escape slashes are removed.
The comments here and here correctly state that in JSON \/
essentially means the same thing as /
, so this is to be expected.
The problem is that I want these forward slashes to remain escaped when I later go to export the JSON data again via json.dumps()
. The JSON file I'm working with should remain as unchanged as possible.
I currently have a hack in place when writing the JSON out after I perform the desired manipulation of the data: json_str.replace('/', '\/')
. This feels ugly to me, or am I mistaken? Is there any better way?
Here is a more complete example:
$ 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"
}
>>>