0

I have a Python function that generates a JSON output. I am trying to see how could I write this to a file.

{'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"}}}

I tried the below:

def output():   <-- This function returns the above JSON data
    json_data()

I tried to write it but creating a new function as below:

def write():
    f = open('results.txt', 'a'). <<- Creates the text file
    f.write(json_data)
    f.close()

This only creates an empty file. Could anyone advice as to how could I write the JSON data to the file.

scott martin
  • 1,253
  • 1
  • 14
  • 36

2 Answers2

0

The output() function isn't returning anything, it needs a return statement:

def output():
    return json_data():

The write() function needs to call the output() function.

def write():
    with open("results.txt", "a") as f:
        f.write(output())
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you want to use the json package I think this works:

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)
Charles Landau
  • 4,187
  • 1
  • 8
  • 24