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

将JavaScript字符串中的特定代码块转为Python字典/JSON时遇JSON解码错误的解决方案咨询

将JavaScript字符串中的特定代码块转为Python字典/JSON时遇JSON解码错误的解决方案咨询

嗨,我看你遇到的问题挺典型的——从JavaScript代码里提取的对象字符串没法直接用Python的json.loads()解析对吧?这个报错的原因很明确:你提取出来的是JavaScript对象字面量,不是严格符合规范的JSON格式。JSON要求所有属性名(键)必须用双引号包裹,但你拿到的字符串里像title、issueSectionTitle这些键都是不带引号的,这就触发了解码错误。

给你两个靠谱的解决方案:

方案一:用正则表达式修复JSON格式

如果你的JS对象键都是合法的标识符(比如没有空格、特殊字符),可以用正则给所有键加上双引号,把它转换成标准JSON:

import re
import json

# 假设这是你从JS代码里提取到的对象字符串
js_obj_str = '{title:"Resident Submitted Details",issueSectionTitle:"Issue",issueDescriptors:{ac__broken__none:"Air Conditioner",air_conditioning__broken__none:"Air Conditioner",air_conditioning__leak__none:"Air Conditioner Leak"}}'

# 匹配所有不带引号的键,替换成带双引号的形式
fixed_json_str = re.sub(r'(\w+):', r'"\1":', js_obj_str)

try:
    json_obj = json.loads(fixed_json_str)
    print(json_obj)
except json.JSONDecodeError as e:
    print(f"解析失败:{e}")

对应到你原来的代码,修改后是这样:

import re
import json

js_code = """你的完整JavaScript代码字符串"""
json_pattern = re.search(r'residentSubmitDetails:\s*({.*?})\s*\}', js_code, re.DOTALL)
print(json_pattern)
if json_pattern:
    json_str = json_pattern.group(1)
    # 修复格式后再解析
    fixed_str = re.sub(r'(\w+):', r'"\1":', json_str)
    try:
        json_obj = json.loads(fixed_str)
        print(json_obj)
    except json.JSONDecodeError as e:
        print(f"解析出错:{e}")

方案二:用专门的库解析JS对象(更稳妥)

如果你的JS对象里有更复杂的语法(比如键包含特殊字符、字符串用单引号、末尾有逗号等),正则就可能失效了。这时可以用支持JS对象语法的json5库,它能直接解析这类非标准JSON:

首先安装库:

pip install json5

然后用json5.loads()替代json.loads():

import re
import json5

js_code = """你的完整JavaScript代码字符串"""
json_pattern = re.search(r'residentSubmitDetails:\s*({.*?})\s*\}', js_code, re.DOTALL)
print(json_pattern)
if json_pattern:
    json_str = json_pattern.group(1)
    # 直接解析JS对象字符串,无需手动修改
    json_obj = json5.loads(json_str)
    print(json_obj)

这个方法兼容性更强,能处理大部分JS对象的写法,推荐优先使用。

备注:内容来源于stack exchange,提问作者Tonin thomas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 08:19:29