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

数据库读取的JSON字符串无法用json.loads解析,变量存储则正常

问题:从数据库读取的JSON字符串无法解析,直接赋值却正常?

错误场景

运行以下代码时触发JSONDecodeError:

import pandas as pd
import json
from sqlalchemy import create_engine

engine = create_engine('你的数据库连接字符串')
df = pd.read_sql(f"select id, jsonresponse from ResponseDetails;", engine)
all_df = df[['id', 'jsonresponse']].values.tolist()

for x in all_df:
   jsn1 = x[1]
   print(jsn1)
   print(json.loads(jsn1))

输出:

{"request_id":"2312","task_id":"423432","group_id":"43r23","success":true,"response_code":"100","response_message":"Valid Authentication"}

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

正常对比场景

把打印出的JSON字符串手动赋值给变量后,json.loads却能正常解析:

jsn2 = '{\"request_id\":\"2312\",\"task_id\":\"423432\",\"group_id\":\"43r23\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}'

print(json.loads(jsn2))

输出:

{'request_id': '2312',
'task_id': '423432',
'group_id': '43r23',
'success': True,
'response_code': '100',
'response_message': 'Valid Authentication'}

无效尝试

试过以下代码,问题仍未解决:

for x in all_df:
    jsn1 = x[1]
    dmp = json.dumps(jsn1)
    print(dmp)
    print(json.loads(dmp))

输出:

"{\\\"request_id\\\":\\\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\\\",\\\"task_id\\\":\\\"ce57782d-a56e-4be7-a803-18dcd71588a2\\\",\\\"group_id\\\":\\\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\\\",\\\"success\\\":true,\\\"response_code\\\":\\\"100\\\",\\\"response_message\\\":\\\"Valid Authentication\\\"}"

{\"request_id\":\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\",\"task_id\":\"ce57782d-a56e-4be7-a803-18dcd71588a2\",\"group_id\":\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}

疑问

  1. jsn1 和 jsn2 为什么会有差异?
  2. 怎么才能正常解析 jsn1?

解答

差异原因

核心区别在于反斜杠的本质:

  • 从数据库读出来的jsn1,里面的\是真实存储的字符——数据库里存的就是带反斜杠的字符串,用来转义双引号。
  • 手动赋值的jsn2,里面的\"是Python的字符串转义符——Python会自动把\"转换成实际的双引号",所以jsn2的真实内容是标准的JSON格式(没有多余反斜杠),自然能被解析。

jsn1里的多余反斜杠会让json.loads混乱:它会把\"当成一个整体字符,而不是被转义的双引号,所以报错说“属性名没被双引号包裹”。

解决方案

方法1:直接替换多余反斜杠

把jsn1里的\全部去掉,再解析:

for x in all_df:
    jsn1 = x[1]
    cleaned_str = jsn1.replace('\\', '')
    result = json.loads(cleaned_str)
    print(result)

方法2:两次JSON解析(更稳妥)

因为数据库里的字符串是“被转义过一次的JSON”,可以先解析一次得到原始JSON字符串,再解析一次拿到字典:

for x in all_df:
    jsn1 = x[1]
    # 第一次解析:把带转义的字符串转成无转义的JSON字符串
    raw_json = json.loads(jsn1)
    # 第二次解析:把JSON字符串转成Python字典
    result = json.loads(raw_json)
    print(result)

方法3:数据库层面直接处理(最优)

如果你的数据库支持JSON类型(比如PostgreSQL、MySQL 5.7+),可以在SQL查询时直接解析JSON,省去后续处理:

-- PostgreSQL:直接把字符串转成JSON类型
SELECT id, jsonresponse::json FROM ResponseDetails;

-- MySQL:去除转义,得到原始JSON字符串
SELECT id, JSON_UNQUOTE(jsonresponse) FROM ResponseDetails;

用这种方式读取后,jsonresponse字段已经是可直接使用的JSON对象(或标准字符串),不需要再调用json.loads。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:05:23