0

I have some code that will take a bunch of JSON files and parse and convert them to csv. I have made it work by taking several JSON files (the output runs on command prompt) but I can't figure out how to make it print a csv file for each given JSON file it starts with.

So here is what I have. At the moment it works just fine one file at a time but as I have hundreds, it's necessary to automate it more so i can handle batches.

All help greatly appreciated. My attempts to piece other people's suggestions to this have not worked :/

import json

file_list = ['file.txt', 'file2.txt'] #insert filename(s) here
for x in range(len(file_list)):
    with open(file_list[x], 'r') as f:
        distros_dict = json.load(f)

    for distro in distros_dict:
        print (str(distro['timestamp'])+ ','+ str(distro['value']))
2
  • 1
    You should use pandas to help you. You can load your json to a pandas DataFrame ( pandas.pydata.org/pandas-docs/stable/generated/…) and then save the DataFrame as csv : df.to_csv("/PATH/TO/FILE.csv",index=False) Commented May 23, 2018 at 12:06
  • Python has a csv module. Commented May 23, 2018 at 12:19

1 Answer 1

1

You can use pandas package.

import pandas as pd
pd.DataFrame.from_dict(distros_dict ['timestamp']['value'])

You dont need to use loop in json

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.