首页 > 解决方案 > 转换为字符串json后无法加载字节Json

问题描述

它在消息中接收的 Json 是一个字节 json,如下所示:b'{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}' 代码应该将字节 Json 更改为 String Json 并加载它以访问项目,但是当我加载它时,我收到以下错误:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

代码:

import json
def handle_msg(topic, message):
    m = message.decode("Utf-8")
    print(json.loads(m))

标签: pythonjsondjango

解决方案


发生这种情况是因为您的消息是空值而不是您预期的如果您编写以下内容它将为您工作以下为我运行

message = b'{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}'
topic ="what ever"
import json 
def handle_msg(topic, message):
    m = message.decode("Utf-8")
    print(json.loads(m))
handle_msg(topic, message)

推荐阅读