You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字节JSON转换为字符串JSON后无法加载的问题求助

Fixing JSONDecodeError When Parsing Byte JSON with HTML Entities

Hey there! Let's break down why your code is throwing that JSONDecodeError and how to fix it.

The Root Cause

The byte data you're receiving has HTML entity-encoded quotes (") instead of standard JSON double quotes ("). When you decode the bytes to a string, you end up with something like this:

'{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}'

The json module can't recognize " as valid JSON syntax—it expects plain " characters, hence the "Expecting value" error at column 1.

The Solution

You need to first convert those HTML entities back to regular characters before parsing the JSON. Python's built-in html module has a handy unescape() function for exactly this.

Here's your modified code:

import json
import html

def handle_msg(topic, message):
    # Decode bytes to string
    m = message.decode("utf-8")
    # Convert HTML entities to regular characters
    unescaped_m = html.unescape(m)
    # Now parse the valid JSON string
    print(json.loads(unescaped_m))

How It Works

  1. message.decode("utf-8") turns your byte data into a string (unchanged from your original code).
  2. html.unescape(m) replaces all HTML entities (like ") with their corresponding characters (so " becomes "). The resulting string will be valid JSON:
    '{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}'
    
  3. json.loads(unescaped_m) can now successfully parse the string into a Python dictionary.

Quick Test

If you want to verify this works, you can run a small test snippet:

import json
import html

test_byte = b'{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}'
s = test_byte.decode("utf-8")
unescaped_s = html.unescape(s)
print(json.loads(unescaped_s))
# Output: {'_timestamp': 1636472787, 'actual': 59.9, 'target': 60.0}

内容的提问来源于stack exchange,提问作者Felix Dango

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:37:30