I can not slash off the screen when converting to JSON . (Python 3.7, Linux)

Now '/' need '\/'

Convert dictionary to json

 d = json.dumps(dic) - слеши в путях к файлам "/" не экранируются 

I try the path = path_raw.replace('/', '\\/')

on the exhaust screen of 4 (!) reverse slashes \\\\/ .

I found an interesting ujson package, it has the option of disabling the slash screening, but it does not work, I tried a bunch of combinations with different quotes and \r'\/' and '\\/' and '\\r\/' .

  • one
    Why screen straight slashes? - insolor
  • slash shielding is needed to export cookies in json format in chrome, in the example of a cookie in json that I found, the slash is shielded, I tried to import without shielding using a chrome plugin, so I suffer - Mikhail Kuligin

2 answers 2

Try this with a hack

 json.dumps(your_dict).replace('/', r'\/') >>> escaped = json.dumps({"path": "/home/com/part/"}).replace('/', r'\/') >>> escaped '{"path": "\\/home\\/com\\/part\\/"}' >>> first_dict = json.loads(escaped) >>> first_dict {'path': '/home/com/part/'} 

Here is described a similar case.

  • Unfortunately, it does not work, json.dumps () escapes the expression when you do not need the "path": "\\ /" and for some reason it does not escape, when necessary - Mikhail Kuligin
  • Corrected added example - VolArt
  • I need a screening after the dump, but only one backslash, and in your example it turns out, after the dump 2 slashes, after extraction everything returns to the original one. But I will not extract from the dump. I need it to be like this: {"path": "\ / com \ /"}. This is not a file path, it is a cookie. In any case, thanks for participating and ideas. - Mikhail Kuligin
  • one
    @MikhailKuligin, this is escaping with one slash. If in the example from this answer print(escaped) , then we get {"path": "\/home\/com\/part\/"} . - insolor 1:58 pm
  • Thank you, you are right! The problem with extra slashes appears at the stage of adding dictionaries to the list, before that everything turns out as it should: I get dictionaries, there is one slash, I do json.dumps (dic) .replace ('/', r '\ /') the slash is screened: { "path": "\ / home \ / com \ / part \ /"}. But when converting to the list of dictionaries, the second screening slash "path" appears: "\\ / complete \\ / search". Now you need to overcome it. - Mikhail Kuligin 5:43 pm

Came here to this solution:

 dic = {'path': /path} listofdic.append(dic) dump_list = json.dumps(listofdic).replace('/', r'\/') str_to_write = str(dump_list) write_file(json_file, str_to_write) 

in the file after recording (I show only the problem piece):

 "path": "\/complete\/search"