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

Python中字符串转JSON时出现特殊字符解析错误

问题

从第三方API获取了如下字符串:

teststring = '{"@speccialcharacterssample": "/special.character.test.Sample","content": {"description": "Some number **451000**, Some Time **Monday, April 8th, UTC 11:00**. \n# BackSpace\nBreakline\nMore Special Character[Full Change Log](https://example.com/v1.0.1).\n# Special Character Test\ncomma test, colon test: breakline\nBreakline followed by hashes test\n## Breakline\nnew test **451000**, time **Monday, April 8th, UTC 11:00**. Square Brackets [HERE](https://example.com/451000).\nThats all.","plan": {"info": "{\\"bin\\":{\\"example/zya32\\":\\"https://example.com/v1.0.1/version-v1.0.1-example-xya32?check=asda43tsd23423scasq\\"}}"}}'

使用以下代码转换为JSON时:

teststring_json = json.loads(teststring)

抛出错误:

teststring_json = json.loads(teststring)
                    ^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 1408 (char 1407)

尝试过updated_json = teststring.replace('\\"', '\\\\"')等移除特殊字符的方法,但均无效,寻求有效解决方法。

解决方案

问题核心是plan.info字段的嵌套JSON字符串未正确转义,导致JSON解析器无法识别字符串边界。以下是三种可行的解决方法:

方法1:手动修正嵌套转义

直接处理嵌套JSON内的引号转义,将内部的\"替换为\\\",确保外层解析时不会误判结束符:

import json

# 修复嵌套JSON的转义问题
fixed_teststring = teststring.replace(r'\"', r'\\\"')
# 解析外层JSON
teststring_json = json.loads(fixed_teststring)
# 解析嵌套的plan.info内容
plan_info_json = json.loads(teststring_json['content']['plan']['info'])

方法2:正则批量修正嵌套转义

如果嵌套结构更复杂,用正则匹配字符串内部未正确转义的引号,批量修正:

import re
import json

# 匹配双引号内未转义的引号并修正
fixed_teststring = re.sub(r'(?<!\\)"(?=(?:[^"]|\\")*"[^}]*$)', r'\\"', teststring)
teststring_json = json.loads(fixed_teststring)
plan_info_json = json.loads(teststring_json['content']['plan']['info'])

方法3:要求API提供者修复输出

从源头解决问题:联系第三方API提供者,要求他们输出符合标准的JSON格式——嵌套的JSON字符串必须正确转义,这是API输出的基本规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:11:05