字节JSON转换为字符串JSON后无法加载的问题求助
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
message.decode("utf-8")turns your byte data into a string (unchanged from your original code).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}'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

