Skip to main content
 首页 » 编程设计

python之如何在 python 中将一个 json 文件作为输出

2024年10月24日11Renyi-Fan

我目前在我的 python 代码中保存一个组合的 json 文件时遇到问题,但它的作用是将最新的“结果”保存在 json 文件中,而不是全部,所以我不得不将所有不同的结果保存在单独的 json 文件中但我想将它存储在单个 faculty.json 文件中,我该怎么做?

这是我的代码:

outputPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output') 
    if os.path.isdir(outputPath) is False: 
        os.makedirs(outputPath) 
    result = {'empid': facultyID, 'name': name, 'school': school, 'designation': designation, 'room': room, 'intercom': intercom, 'email': email, 'division': division, 'open_hours': openHours} 
    with open('output/faculty.json', 'w') as outfile: 
        json.dump(result, outfile) 
    return result 

请您参考如下方法:

您可以将所有 dict 收集到一个列表中,然后将该列表保存为 JSON 文件。这是该过程的简单演示。该程序重新加载 JSON 文件以验证它是合法的 JSON 并且它包含我们期望的内容。

import json 
 
#Build a simple list of dicts 
s = 'abcdefg' 
data = [] 
for i, c in enumerate(s, 1): 
    d = dict(name=c, number=i) 
    data.append(d) 
 
fname = 'data.json' 
 
#Save data 
with open(fname, 'w') as f: 
    json.dump(data, f, indent=4) 
 
#Reload data 
with open(fname, 'r') as f: 
    newdata = json.load(f) 
 
#Show all the data we just read in 
print(json.dumps(newdata, indent=4)) 

输出

[ 
    { 
        "number": 1,  
        "name": "a" 
    },  
    { 
        "number": 2,  
        "name": "b" 
    },  
    { 
        "number": 3,  
        "name": "c" 
    },  
    { 
        "number": 4,  
        "name": "d" 
    },  
    { 
        "number": 5,  
        "name": "e" 
    },  
    { 
        "number": 6,  
        "name": "f" 
    },  
    { 
        "number": 7,  
        "name": "g" 
    } 
]