2

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"
}
>>> 
boltronics
  • 35
  • 6
  • *"The comments here and here correctly state that in JSON \/ essentially means the same thing as /, however I still don't want Python changing it."* So, you want JSON parser to misbehave? It is not *changing* it - it is correctly parsing the escape sequence it finds in JSON. Would you also not want it to *change* `\n` to a newline character? Maybe you want to write own *"AlmostJSON"* parser... – zvone Jun 07 '18 at 07:22
  • The main question is: why? Why do you even have a JSON with `\/` in it? Why do you want a path like `\/home\/user\/test.txt`? If you want backshashes in JSON, why don't you have them correctly escaped when creating JSON? – zvone Jun 07 '18 at 07:26
  • 1
    Fair enough - I probably shouldn't include the slashes when reading but just when writing the file out via `json.jumps()`. I'll update my question accordingly. To answer why I even have JSON like that, it's loaded by a different program by another author in another language. I also need to be able to display a diff of my final changes to the string, which I'm using `difflib.unified_diff()` for. Having the JSON file altered more than necessary is what I want to avoid. – boltronics Jun 07 '18 at 07:47

0 Answers0