Skip to main content
 首页 » 编程设计

Python之将附加的 "members"传递给函数时附加到 JSON 对象

2025年05月04日9www_RR

我有以下 JSON 对象位于其自己的名为 build.json 的文件中:

{ 
    "name": "utils", 
    "version": "1.0.0", 
    "includes": [], 
    "libraries": [], 
    "testLibraries": [] 
} 

我使用以下方法在我的 Python 程序中获取此对象:

def getPackage(packageName): 
    jsonFilePath = os.path.join(SRCDIR, packageName, "build.json") 
    packageJson = None 
    try: 
        with open(jsonFilePath, "r") as jsonFile: 
            packageJson = json.load(jsonFile) 
    except: 
        return None 
    return packageJson 

我验证当前包(这是我正在迭代的众多包之一)的 JSON 对象没有在以下方法中返回 None。请注意,我暂时打印出字典的键:

def compileAllPackages(): 
    global COMPILED_PACKAGES 
 
    for packageName in os.listdir(SRCDIR): 
        package = getPackage(packageName) 
        if package == None: 
            continue 
 
        # TEMP ============== 
        for i in package: 
            print(i) 
        # =================== 
 
        compiledSuccessfully = compilePackage(package) 
        if not compiledSuccessfully: 
            return False 
    return True 

最后,我目前还在 compilePackage 函数中接收到字典的键后打印出它:

def compilePackage(package): 
    global COMPILED_PACKAGES, INCLUDE_TESTS 
 
    # TEMP ============== 
    for i in package: 
        print(i) 
    # ===================         
 
    ... 

compileAllPackages 函数的输出:

name 
version 
includes 
libraries 
testLibraries 

compilePackage 函数的输出:

name 
version 
includes 
libraries 
testLibraries 
u 
t 
i 
l 
s 

我这辈子都无法弄清楚在该函数调用期间我的字典发生了什么???请注意,build.json 文件位于名为“utils”的目录中。

编辑: Python 脚本与 build.json 文件分开放置,并在绝对路径上运行。还应该注意的是,在得到那个奇怪的输出后,我在稍后尝试访问有效 key 时也得到以下异常(它似乎认为字典是一个字符串?......):

Traceback (most recent call last): 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 493, in <module> 
    main() 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 481, in main 
    compiledSuccessfully = compileAllPackages() 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 263, in compileAllPackages 
    compiledSuccessfully = compilePackage(package) 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 287, in compilePackage 
    compiledSuccessfully = compilePackage(include) 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 279, in compilePackage 
    includes = getPackageIncludes(package) 
  File "/Users/nate/bin/BuildTool/unix/build.py", line 194, in getPackageIncludes 
    includes = [package["name"]]    # A package always includes itself 
TypeError: string indices must be integers 

编辑:如果我将参数名称更改为“package”以外的名称,以后我将不再获得奇怪的输出或异常。但是,这不一定是修复,因为我不知道名称“package”可能有什么问题。也没有这样命名的全局变量。

请您参考如下方法:

答案最终变得非常愚蠢。由于包可能依赖的任何依赖项,compilePackage() 有可能被递归调用。在对函数的递归调用中,我将字符串而不是字典传递给函数。