Home > other >  How can I edit my code to print out the content of my created json file?
How can I edit my code to print out the content of my created json file?

Time:10-13

My program takes a csv file as input and writes it as an output file in json format. On the final line, I use the print command to output the contents of the json format file to the screen. However, it does not print out the json file contents and I don't understand why.

Here is my code that I have so far:

import csv 
import json

def jsonformat(infile,outfile):
    contents = {}
    csvfile = open(infile, 'r')
    reader = csvfile.read()

    for m in reader:
        key = m['No']
        contents[key] = m
    
    jsonfile = open(outfile, 'w')
    jsonfile.write(json.dumps(contents))

    csvfile.close()
    jsonfile.close()
    return jsonfile

infile = 'orders.csv'
outfile = 'orders.json'

output = jsonformat(infile,outfile)

print(output)

CodePudding user response:

Your function returns the jsonfile variable, which is a file.
Try adding this:

jsonfile.close()
with open(outfile, 'r') as file:
    return file.read()

CodePudding user response:

Your function returns a file handle to the file jsonfile that you then print. Instead, return the contents that you wrote to that file. Since you opened the file in w mode, any previous contents are removed before writing the new contents, so the contents of your file are going to be whatever you just wrote to it.

In your function, do:

def jsonformat(infile,outfile):

    ...

    # Instead of this:
    # jsonfile.write(json.dumps(contents))


    # do this:
    json_contents = json.dumps(contents, indent=4) # indent=4 to pretty-print
    jsonfile.write(json_contents)

    ...

    return json_contents

CodePudding user response:

a_file = open("sample.json", "r")
a_json = json.load(a_file)
pretty_json = json.dumps(a_json, indent=4)
a_file.close()

print(pretty_json)

Using this sample to print the contents of your json file. Have a good day.

  • Related