How to remove Unicode characters from dictionary data in python

After using the request library, I get below dict in response.json ()

{u'xyz': {u'key1': None, u'key2': u'Value2'}}

I want to delete all unicode characters and print only key value pairs without unicode characters

I tried using the method below, but it shows the wrong string

>>> import json, ast
>>> c = {u'xyz': {u'key1': None,u'key2': u'Value2'}}
>>> ast.literal_eval(json.dumps(c))

Getting 'ValueError: invalid string'

Any suggestion on how to do this?

+4
source share
3 answers

you can use unicodestring.encode("ascii","replace")

>>> ustr=u'apple'
>>> ustr
u'apple'
>>> astr=ustr.encode("ascii","replace")
>>> astr
'apple'
0
source

Change the value "No" to "No":

 c = {u'xyz': {u'key1': 'None', u'key2': u'Value2'}}

it's a casting question - ast loves str's

, , None, str "None" str... : Python: None ? "" :

def xstr(s):
    if s is None:
        return 'None'
    return str(s)
+3

, . Python Unicode, , , u'', , .

, , JSON - . .json() , response .text - JSON, .

>>> ast.literal_eval(json.dumps(c))

Fails because you flip it cto JSON first and then try to parse it as a Python literal. This does not work because Python is not JSON; in particular, has null, and the other has None.

So maybe you want to change Unicode strings to bytes? For example, encoding them as UTF8, this may work:

def to_utf8(d):
    if type(d) is dict:
        result = {}
        for key, value in d.items():
            result[to_utf8(key)] = to_utf8(value)
    elif type(d) is unicode:
        return d.encode('utf8')
    else:
        return d

Or something like that, but I don’t know why you need it.

-2
source

All Articles