如何在 python 中使用 unicode 解码字符串?
How to decode string with unicode in python?
我有以下行:
%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22
预期结果:
{"appVersion":1,"modulePrefix":"web-experience-app","environment":"production","rootURL":"/","
你可以去看看here。
我尝试了什么:
foo = '%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22'
codecs.decode(foo, 'unicode-escape')
foo.encode('utf-8').decode('utf-8')
这不起作用。还有哪些其他选择?
字符串已进行 urlencoded。您可以通过反转urlencoding来转换它。
from urllib import parse
s = '%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22'
unquoted = parse.unquote(s)
unquoted
'{"appVersion":1,"modulePrefix":"web-experience-app","environment":"production","rootURL":"/","'
这看起来像是更大的 JSON 字符串的一部分。完整的对象可以用 json.loads
.
反序列化
我有以下行:
%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22
预期结果:
{"appVersion":1,"modulePrefix":"web-experience-app","environment":"production","rootURL":"/","
你可以去看看here。 我尝试了什么:
foo = '%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22'
codecs.decode(foo, 'unicode-escape')
foo.encode('utf-8').decode('utf-8')
这不起作用。还有哪些其他选择?
字符串已进行 urlencoded。您可以通过反转urlencoding来转换它。
from urllib import parse
s = '%7B%22appVersion%22%3A1%2C%22modulePrefix%22%3A%22web-experience-app%22%2C%22environment%22%3A%22production%22%2C%22rootURL%22%3A%22/%22%2C%22'
unquoted = parse.unquote(s)
unquoted
'{"appVersion":1,"modulePrefix":"web-experience-app","environment":"production","rootURL":"/","'
这看起来像是更大的 JSON 字符串的一部分。完整的对象可以用 json.loads
.