删除 json 列表中的 u'

Remove u' in json list

我有一个 python 脚本可以查询返回一组信息的服务器。 我需要将其放入 php 网站使用的数据库中。怎么会有一个特定的字段,我得到 returned description 字段,这是用户输入的,在某些情况下,使用了一些 ASCII 字符,但在我将它放入数据库之前,我必须转换它到utf-8。一切顺利,但它给我留下了一个问题,因为它 return 一个带有 u' 个字符的 JSON 数组,这使得它不可读

我正在对输入执行以下操作:

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

return我是以下字符串

{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'}]}

虽然我需要这样的东西:

{"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":""}

作为一个没有 python 经验的人,我不知道如何解决这个问题,我尝试了几种不同的编码方式,希望结果会有所不同

status.description.encode('utf8')

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

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

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

还有一些使用 ASCII,但到目前为止还没有骰子。

有什么方法可以在我将它放入数据库之前从列表中删除这个 u 但仍然使用 utf8 编码? (或者如果可能,通过 php)

如果 status.description 正在返回一个字典,而您希望它是 JSON,您应该对其调用 json.dumps(),而不是 unicode()

但是,字典中存在 u 个字符不是问题,不需要修复。

print(some_dict) 打印 dict 对象的字符串表示形式。您需要将 dict 对象转换为 JSON.

import json
print(json.dumps(some_dict))