簡體   English   中英

在json列表中刪除u'

[英]Remove u' in json list

我有一個python腳本,用於查詢返回了一組信息的服務器。 我需要將其放到PHP網站使用的數據庫中。 但是我有一個特定字段返回給用戶輸入的description字段,在某些情況下會使用一些ASCII字符,但是在將其放入數據庫之前,我必須將其轉換為utf-8。 一切正常,但給我帶來了一個問題,因為它返回帶有u'字符的JSON數組,這使其難以讀取

我正在對輸入執行以下操作:

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

返回我以下字符串

{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返回一個dict並且您希望它是JSON,則應在其上調用json.dumps() ,而不是unicode()

但是,字典中包含u字符不是問題,不需要修復。

print(some_dict) dict對象的打印字符串表示形式。 您需要將dict對象轉換為JSON。

import json
print(json.dumps(some_dict))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM