Timo Timo - 3 months ago 17
Python Question

Remove u' in json list

I have a python script that queries servers that comes back with a set of information.
Which i need to put into a database which is used by a php website. How ever there is a specific field that i get returned the

description
field which is user input and in some cases a few ASCII characters are used but before i can put this in the database i have to convert it to utf-8. It goes all right but it leaves me with a problem as it return a JSON array with
u'
characters which makes it unreadable

I am doing the following to the input:

unicode(status.description).encode('utf8')


Which returns me the following string

{u'text': u'', u'extra': [{u'color': u'white', u'text': u' '}, {u'color': u'dark_gray', u'text': u'\xbb '}, {u'color': u'gold', u'text': u'Velocity', u'bold': True}, {u'color': u'red', u'text': u'MC ', u'bold': True}, {u'color': u'dark_gray', u'text': u'\xab\n'}, {u'color': u'white', u'text': u' '}, {u'color': u'gray', u'text': u'\u25b6 '}, {u'color': u'yellow', u'text': u'HCF SOTW ', u'bold': True}, {u'color': u'red', u'text': u'8/28 ', u'italic': True}, {u'color': u'gold', u'text': u'3PM EST ', u'italic': True}, {u'color': u'gray', u'text': u'\u25c0'}]}


While i need something like:

{"extra":[{"text":" ","color":"white"},{"text":"» ","color":"dark_gray"},{"text":"Velocity","color":"gold","bold":true},{"text":"MC ","color":"red","bold":true},{"text":"«\n","color":"dark_gray"},{"text":" ","color":"white"},{"text":"▶ ","color":"gray"},{"text":"2.0 ","color":"red","bold":true},{"text":"OPFACTIONS HAS BEEN RELEASED ","color":"yellow","bold":true},{"text":"◀","color":"gray"}],"text":""}


As someone not that experienced with python i have no idea how i could solve this i tried a few different ways of encoding it like hoping it would turn out different

status.description.encode('utf8')


unicode(status.description).encode('utf8')


status.description.encode('utf-8')


unicode(status.description).encode('utf-8')


And a few with ASCII but so far no dice.

Is there a way i can remove this
u
from the list before i put it in the database but still have it utf8 encoded? (Or via php if possible)

Answer

If status.description is returning a dict and you want it to be JSON, you should call json.dumps() on it, not unicode().

However, the presence of u characters in a dict is not a problem and does not need to be fixed.

Comments