【问题标题】:Using json.loads in Python 2.7 returns unicode object instead of dict在 Python 2.7 中使用 json.loads 返回 unicode 对象而不是 dict
【发布时间】:2016-09-07 22:26:52
【问题描述】:

我在将 JSON 数据解析为我无法弄清楚的字典时遇到了问题。

我正在从 JavaScript 连接到 Tornado 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)

由此产生的输出是:

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

现在我希望第二条打印的消息是dict,但我不知道为什么这不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 对不起,如果我误解了,但是 content: {"action":"START_QUESTION_SELF"} 实际上是一个字典。
  • 你用的是python2还是3?
  • @M.T,我使用的是 Python 2.7
  • @SerhanOztekin 它作为 unicode 字符串被接收,在调用 json.loads() 后它仍然被视为 unicode 对象,我不能将其用作字典。
  • 我无法使用 python 2.7 重现这一点。我得到Parsed message type: &lt;type 'dict'&gt;

标签: javascript python json dictionary unicode


【解决方案1】:

它不起作用,因为当您发送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)));

【讨论】:

  • 我将数据的发送更改为:sock.send(JSON.stringify(JSON.parse($('textfield').value))); 现在在 Python 端获得一个 dict。谢谢!
  • @Revell Huh。我刚刚提出了相同的解决方案:)
【解决方案2】:

我似乎您的字符串已转义 (\"),因此 json.loads 将其视为纯字符串。
在调用json.loads 之前尝试取消转义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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 2018-04-26
    • 1970-01-01
    • 2017-09-13
    • 2016-11-07
    • 2019-05-04
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多