【问题标题】:Python - Writing JSON data to file [duplicate]Python - 将 JSON 数据写入文件 [重复]
【发布时间】: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() 不返回任何内容
  • @OlvinR​​oght,我尝试将早期函数 (def output()) 的输出写入 def write 函数

标签: python json


【解决方案1】:

output() 函数没有返回任何内容,它需要一个 return 语句:

def output():
    return json_data():

write()函数需要调用output()函数。

def write():
    with open("results.txt", "a") as f:
        f.write(output())

【讨论】:

    【解决方案2】:

    如果你想使用 json 包,我认为这可行:

    import json
    json_src = """{'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"}}}"""
    
    # Can be wrapped in your write() function if you so choose
    with open("results.txt", "a") as file:
      json.dump(json_src, file)
    

    【讨论】:

    • 能否请您帮忙弄清楚如何将 JSON 输出存储到 def output () 中的变量中
    猜你喜欢
    • 2013-04-22
    • 2016-12-07
    • 1970-01-01
    • 2018-02-02
    • 2019-02-22
    • 2018-05-26
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多