Sisyphus
Sisyphus

Reputation: 926

How to convert a python object to string with non-ascii character unchanged?

I have an object like:

obj1 = {
    'k1' : 'v1', 
    'k2' : [
        {
            'k21' : '中文字符'
        }
    ]
}

I want to convert it to a string like :

'''{ 'k1' : 'v1', 'k2' : [ { 'k21' : '中文字符' } ] } '''

using str() give me this:

'''{'k2': [{'k21': '\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6'}], 'k1': 'v1'}'''

Notice that '\xe4' has four chars. I guess that str() simply calls repr().

One solution is traveling all the key of the object and recursively handle it. I am wondering is there any other way to achieve it. Such as converting the '\xe4' to '中' or directly convert obj1 to the excepted result.

Thanks!

Upvotes: 0

Views: 116

Answers (1)

Anzel
Anzel

Reputation: 20563

Like what @Cyber suggested, using json will be an option, like this:

import json

In [11]: obj1 = {
    ...:     'k1' : 'v1', 
    ...:     'k2' : [
    ...:         {
    ...:             'k21' : '中文字符'
    ...:         }
    ...:     ]
    ...: }
         # remember to set ensure_ascii=False
In [12]: s = json.dumps(obj1, ensure_ascii=False)

In [13]: print s
{"k2": [{"k21": "中文字符"}], "k1": "v1"}

I'm on Python 2.7.8

Upvotes: 1

Related Questions