简体   繁体   中英

How to save/get redis hash key as unicode?

When I get a hash map key:value from redis, it turns out to be like:

hmgetall {'<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>': '1'}

While it is saved as unicoe in python.

So I'm wondering how to save the hash key as unicode so that it can be compared with unicode strings?

I'd like the key to be saved into it's unicode format which is:

   key =  '<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'

Or, otherwise, I'd like to be able to convert the key to \\xd8\\xb1\\xd8\\xaf\\... format so that I can compare it with redis' saved key.

I've looked at the docs but could not find hints about this.

Assuming you're using Python 2, and the keys/values are encoded as utf-8:

>>> redis_key = '<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>'
>>> redis_key.decode('utf-8')
u'<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'

To encode an existing key:

>>> key = u'<a href="/topic/\u0631\u062f\u06cc\u0633-\u062a\u0633\u062a">\u0631\u062f\u06cc\u0633 \u062a\u0633\u062a</a>'
>>> key.encode('utf-8')
'<a href="/topic/\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3-\xd8\xaa\xd8\xb3\xd8\xaa">\xd8\xb1\xd8\xaf\xdb\x8c\xd8\xb3 \xd8\xaa\xd8\xb3\xd8\xaa</a>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM