This article describes how to parse the string encoded by the JavaScript escape function in Python, that is, how to restore the string encoded by the JavaScriptescape function in Python, you can refer to a problem you may encounter. you need to use Python to restore the escape in JavaScript. but after a long time, you have not found the answer, so you have to study the solution on your own.
Let's take a look at the encoding of a text section of escape in js.
The code is as follows:
A = escape ('This is a string of text ');
Alert ();
Output:
The code is as follows:
% U8FD9 % u662F % u4E00 % u4E32 % u6587 % u5B57
At first glance, it seems a bit similar to the json format. let's take a look at the man with the same standard json Format Encoding "this is a string of text"
The code is as follows:
# Encoding = UTF-8
Import json
A = 'This is a string of text'
Print json. dumps ()
Output:
The code is as follows:
"\ U8fd9 \ u662f \ u4e00 \ u4e32 \ u6587 \ u5b57"
After comparison, in fact, each man in js escape encoding is a "% u" symbol plus a four-character encoding, while each man in json encoding is a "\ u" symbol plus a four-character encoding, in this case, we can use the string replacement operation to restore the json format, and then use the json module loads.
The code is as follows:
# Encoding = UTF-8
Import json
# Js escape string encoding
C = '% u8FD9 % u662F % u4E00 % u4E32 % u6587 % u5B57'
# Restore a Json object
JsonObj = '"' +" ". join ([(I and" \ "+ I) for I in c. split ('%')]) + '"'
Print json. loads (jsonObj)
In particular, after replacing "%" with the "\" symbol, you must use double quotation marks to pack the string to make it a json object and then use json. loads.
Later, I found a simpler method on a website. The code is as follows:
The code is as follows:
# Encoding = UTF-8
C = '% u8FD9 % u662F % u4E00 % u4E32 % u6587 % u5B57'
Print "". join ([(len (I)> 0 and unichr (int (I, 16) or "") for I in c. split ('% u')])
In fact, the idea is similar. replace "% u", and the rest are 4 characters of fixed length encoding. finally, unichr uncodes back the Chinese characters.