Python Forum
How to exctract this json to csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to exctract this json to csv
#5
sys.argv[1] and/or sys.argv[2] will never be None. In case it is missing, you will get IndexError the moment when you try to access element with non-existing index in sys.argv. You may look at click for creating nice cli interface. Or at least at argparse module from standard library.

import json
import sys
import csv
import pandas as pd


try:
    _, json_file, csv_file = sys.argv
except ValueError:
    print(f'Incorrect number of CLI arguments.\nUse: yourscript.py json_file csv_file')
else:
    with open(json_file) as f:
        data = json.load(f)

    # using csv
    with open(csv_file, 'w') as f:
        wrtr = csv.DictWriter(f, fieldnames=data['all-services'][0].keys())
        wrtr.writeheader()
        wrtr.writerows(data['all-services'])

    # alternative - usnig pandas
    df = pd.json_normalize(data['all-services'])
    df.to_csv(csv_file, index=False)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
How to exctract this json to csv - by kahlenberg - May-03-2020, 05:25 PM
RE: How to exctract this json to csv - by ndc85430 - May-03-2020, 05:44 PM
RE: How to exctract this json to csv - by buran - May-03-2020, 05:52 PM
RE: How to exctract this json to csv - by buran - May-04-2020, 05:22 AM
RE: How to exctract this json to csv - by buran - May-04-2020, 09:41 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020