【发布时间】:2019-05-09 11:50:41
【问题描述】:
我有一个生成 JSON 输出的 Python 函数。我正在尝试查看如何将其写入文件。
{'logs': ['3982f208'], 'events': [{'sequence_number': 06972977357, 'labels': [], 'timestamp': 1556539666498, 'message': 'abc [2015-12-19 12:07:38.966] INFO [b5e04d2f5948] [ProcessController] PRMS: {"MessageType"=>"TYPE1", "Content"=>{"Name"=>"name1", "Country"=>"europe", "ID"=>"345", "Key1"=>"634229"}}}
我尝试了以下方法:
def output(): <-- This function returns the above JSON data
json_data()
我尝试编写它,但创建了一个新函数,如下所示:
def write():
f = open('results.txt', 'a'). <<- Creates the text file
f.write(json_data)
f.close()
这只会创建一个空文件。谁能建议我如何将 JSON 数据写入文件。
【问题讨论】:
-
什么是
json_data?有没有报错? -
这不是 JSON,您必须使用
json.dump()。 -
那是无效的 JSON
-
output()不返回任何内容 -
@OlvinRoght,我尝试将早期函数 (
def output()) 的输出写入def write函数