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

Python如何正确读取不可修改的config.js文件 解决slimit字段混淆问题

解决方案

你之前使用slimit的问题在于直接将所有赋值节点扁平化存储到同一个字典中,相同键名会被后续出现的同名字段覆盖,同时丢失了嵌套层级信息,所以才会出现db下的database被anotherconfig下的database覆盖的问题。下面提供两种可直接使用的方案,均不需要修改原config.js文件:

方案1:调用Node.js子进程解析(最稳妥)

该方案直接使用JS运行时读取配置,100%和JS侧获取的配置内容完全一致,无需处理JS语法、注释、嵌套等兼容问题,适合你的技术栈同时包含Node.js环境的场景。

import subprocess
import json

config_path = r"C:\path\to\config copy.js"
# 调用Node读取配置并输出JSON格式
result = subprocess.run(
    ["node", "-e", "console.log(JSON.stringify(require(process.argv[1])))", config_path],
    capture_output=True,
    text=True,
    check=True
)
config = json.loads(result.stdout)

# 直接按层级读取所需配置即可
print(config["db"]["database"])       # 输出:somebase
print(config["anotherconfig"]["database"])  # 输出:anotherdatabase

方案2:纯Python解析JS AST(无Node依赖)

如果环境中无法安装Node.js,可以使用pyjsparser库解析JS语法树,递归构建嵌套的配置字典,完整保留层级关系:

  1. 先安装依赖:
pip install pyjsparser
  1. 解析代码:
import pyjsparser
from pyjsparser import ast

def parse_js_node(node):
    # 递归解析JS节点为Python类型
    if isinstance(node, ast.ObjectExpression):
        obj = {}
        for prop in node.properties:
            # 处理对象键名
            if hasattr(prop.key, "value"):
                key = prop.key.value
            else:
                key = prop.key.name
            obj[key] = parse_js_node(prop.value)
        return obj
    elif isinstance(node, ast.ArrayExpression):
        return [parse_js_node(elem) for elem in node.elements]
    elif isinstance(node, ast.Literal):
        return node.value
    else:
        # 可根据实际需要扩展其他JS类型的解析逻辑
        return None

if __name__ == "__main__":
    with open(r"C:\path\to\config copy.js", "r", encoding="utf-8") as f:
        js_content = f.read()
    ast_tree = pyjsparser.parse(js_content)
    # 查找module.exports的赋值节点
    config_root = None
    for node in ast_tree.body:
        if (isinstance(node, ast.ExpressionStatement) 
            and isinstance(node.expression, ast.AssignExpression)):
            left = node.expression.left
            if (isinstance(left, ast.MemberExpression) 
                and left.object.name == "module" 
                and left.property.name == "exports"):
                config_root = node.expression.right
                break
    config = parse_js_node(config_root)
    # 按层级读取配置
    print(config["db"]["pass"])
    print(config["db"]["servers"][0]["host"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:48:05