0

I am trying to parse unicode string in python and run into Invalid \escape error. I have seen this post, but it didn't help either.

Here's my code:

def replace_with_byte(match):
    return chr(int(match.group(0)[1:], 8))

def test(request):
    params = RequestLog.objects.get(id = request_id).params
    params = params[2:len(params)-1]
    invalid_escape = re.compile(r'\\[0-7]{1,3}')
    params = invalid_escape.sub(replace_with_byte, params)
    params = json.loads(params) # The error rises here
    # ...

And here's the value of params:

[{"display_name":"My calendar","owner_account":"My calendar","client_id":"1","name":"My calendar"},{"display_name":"navasardyan.edgar@gmail.com","owner_account":"navasardyan.edgar@gmail.com","client_id":"2","color":"15","name":"navasardyan.edgar@gmail.com"},{"display_name":"Contacts","owner_account":"#contacts@group.v.calendar.google.com","client_id":"3","color":"9","name":"Contacts"},{"display_name":"Holidays in Armenia","owner_account":"en.am#holiday@group.v.calendar.google.com","client_id":"4","color":"17","name":"Holidays in Armenia"},{"display_name":"\xd0\x9f\xd1\x80\xd0\xb0\xd0\xb7\xd0\xb4\xd0\xbd\xd0\xb8\xd0\xba\xd0\xb8 \xd0\xa0\xd0\xa4","owner_account":"ru.russian#holiday@group.v.calendar.google.com","client_id":"5","color":"12","name":"\xd0\x9f\xd1\x80\xd0\xb0\xd0\xb7\xd0\xb4\xd0\xbd\xd0\xb8\xd0\xba\xd0\xb8 \xd0\xa0\xd0\xa4"},{"display_name":"Test","owner_account":"0nptlmsb73cnqbsj204ng35c5k@group.calendar.google.com","client_id":"6","color":"18","name":"Test"},{"display_name":"navasardyan.edgar@outlook.com","owner_account":"navasardyan.edgar@outlook.com","client_id":"7"}]

The error message as is:

json.decoder.JSONDecodeError: Invalid \escape: line 1 column 563 (char 562)

martineau
  • 119,623
  • 25
  • 170
  • 301
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121
  • I can't reproduce the error (after setting `params` equal to a _string_ containing what you say its value is (at the point `invalid_escape.sub()` is called I assume). Please provide a MCVE that reproduces the problem. See [**How to create a Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve) – martineau Oct 26 '17 at 15:45
  • Try a solution from this post https://stackoverflow.com/a/4296045 – PyKaB Oct 31 '17 at 06:58
  • Does this answer your question? [simplejson.loads() get Invalid \escape: 'x'](https://stackoverflow.com/questions/4296041/simplejson-loads-get-invalid-escape-x) – user202729 Feb 17 '21 at 11:49

0 Answers0