2016-05-12 27 views
1

我遇到了將JSON數據解析爲字典的問題,我無法弄清楚。在Python 2.7中使用json.loads會返回unicode對象而不是字典

我連接到從JavaScript龍捲風的WebSocket發送以下數據,輸入到文本框:

{"action": "something"} 

我送它到的WebSocket的方法是:

sock.send(JSON.stringify($('textfield').value)); 

現在在Python我有我的WebsocketHandler()下面的代碼:: ON_MESSAGE:

print("Message type: " + str(type(message)) + ", content: " + message) 

parsed_message = json.loads(message) 

print("Parsed message type: " + str(type(parsed_message)) + ", content: " + parsed_message) 

和TH從這個網絡輸出爲:

Message type: <type 'unicode'>, content: "{\"action\":\"START_QUESTION_SELF\"}" 
Parsed message type: <type 'unicode'>, content: {"action":"START_QUESTION_SELF"} 

現在我希望第二印刷信息是dict,我想不通這是爲什麼不工作。任何幫助將不勝感激。

+0

對不起時,我有同樣的錯誤,如果我誤解了,但內容:{「行動」 :「START_QUESTION_SELF」}實際上是一個字典。 –

+0

你使用的是python2還是3? –

+0

@ M.T,我正在使用Python 2.7 – Revell

回答

3

,因爲當你做sock.send(JSON.stringify('{"action": "something"}'));當您打印郵件,你可以驗證它實際上包含引號您發送此"{\"action\": \"something\"}"

它不工作。因此,它被json.loads解釋爲一個字符串。

最簡單的辦法將再次調用json.loads

parsed_message = json.loads(json.loads(message)) 

但是你真的應該考慮文本字段值轉換成一個對象,然後用它JSON.stringify。事情是這樣的:

sock.send(JSON.stringify(JSON.parse($('textfield').value))); 
+0

我改變的數據來發送: 'sock.send(JSON.stringify(JSON.parse($( '文本框')值)));' 現在得到一個關於Python結尾的字典。謝謝! – Revell

+0

@Revell Huh。我剛剛提出了同樣的解決方案:) – Alik

0

我好像你的字符串被轉義(\"),從而json.loads認爲這是一個普通的字符串。
致電json.loads之前,嘗試使用unescape message

在模型中使用JSONField和JSON而不是設置這個

content='{"content":"Hello A","numbers":[1,2,3,4]}' 
# json.loads(model.content) --> type 'str' 

content={"content":"Hello A","numbers":[1,2,3,4]} 
# json.loads(model.content) --> type 'dict' 
相關問題