Home > Mobile >  How can I write filtered results from a JSON file to a CSV file in Python?
How can I write filtered results from a JSON file to a CSV file in Python?

Time:11-10

I am trying to make a program that can save the results of a filtered JSON file as a CSV. Right now my function only saves the keys of the JSON to the CSV file.

Ideally I want the function to take two arguments: column (key) it is searching in; and the item (value) it is searching for.

This is my current function:

def save_csv(key, value):
    with open('db.json') as json_file:
        info = json.load(json_file)
    test = info['data']

    csv_file = open('test.csv', 'w')
    csv_writer = csv.writer(csv_file)
    count = 0
    for e in test:
        if count == 0:
            header_csv = e.keys()
            csv_writer.writerow(header_csv)
            count  = 1

    for e in key:
        if e == value:
            csv_writer.writerow(e.values())
    csv_file.close()

How could I change this function to make it save the filtered results in a CSV?

No matter what changes I try to make, it will only save the keys to the header of the CSV. None of the results I am filtering for will save to the CSV.

CodePudding user response:

Not really an answer, just a correction to your code that I think might help.

    with open('test.csv', 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        count = 0
        for e in test:
            if count == 0:
                header_csv = e.keys()
                csv_writer.writerow(header_csv)
                count  = 1
             else:
                for ky in key:
                  if ky == value:
                     csv_writer.writerow(e.values())
            #csv_file.close() No need to do when using with

CodePudding user response:

def save_csv(key, value):
    with open('db.json') as json_file:
        info = json.load(json_file)
        test = info['data']
        with open('test.csv', 'w', newline='') as csv_file:
            csv_writer = csv.writer(csv_file)
            for n,v in enumerate(test):
                if not n:
                    header_csv = e.keys()
                    csv_writer.writerow(header_csv)
                if key in v and v.get(key)==value:
                    csv_writer.writerow(e.values())
  • Related