how to convert json to csv in python

后端 未结 4 833
时光取名叫无心
时光取名叫无心 2020-12-19 22:27

Following is my json file input

{\"userID\": \"679d3bad-155e-4b39-9ff7-7d564f408942\", \"Is salary credited before 5th\": \"Yes\", \"Avg Salary of last 3 mon         


        
相关标签:
4条回答
  • 2020-12-19 23:10

    You can do this: Read your JSON and write-in a CSV file with importing json and csv modules

    import json, csv
    from collections import OrderedDict #To maintain key value pair order
    _json=json.loads(open('data.json', 'r').read(), object_pairs_hook=OrderedDict) 
    out=open('converted.csv', 'w')
    writer = csv.writer(out)               #create a csv.write
    writer.writerow(_json[0].keys())      # header row
    for row in _json:
        writer.writerow(row.values())
    
    0 讨论(0)
  • 2020-12-19 23:14

    GeekSambhu's solution worked for me with a minor modification. I modified it a little because like Vinsent, I saw a KeyError. People may be getting the KeyError if the JSON structure has a top level object holding the array of the rows of data (this is considered a JSON best practice). Assuming a top level object called 'data', you would change only two lines of code of GeekSambhu's solution.

    writer.writerow(_json['data'][0].keys()) # header row
    for row in _json['data']:

    0 讨论(0)
  • 2020-12-19 23:19

    BankData is a dict you do not need to iterate it. You can directly access the values using the key.

    Ex:

    import csv
    import json
    
    with open('/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.json') as infile:
        BankData = json.loads(infile.read())
    
    with open("/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.csv", "w") as outfile:
        f = csv.writer(outfile)
        f.writerow(["userID", "Is salary credited before 5th", "Avg Salary of last 3 months", "Avg Salary of last 6 months", "Avg Balance before salary of last 3 months", "Avg Balance before salary of last 6 months"])
        f.writerow([BankData["userID"], BankData["Is salary credited before 5th"],
                    BankData["Avg Salary of last 3 months"],
                    BankData["Avg Salary of last 6 months"],
                    BankData["Avg Balance before salary of last 3 months"],
                    BankData["Avg Balance before salary of last 6 months"]])
    
    0 讨论(0)
  • 2020-12-19 23:19

    You can also use pandas to handle dataframe,

    dct = {"userID": "679d3bad-155e-4b39-9ff7-7d564f408942", "Is salary credited before 5th": "Yes", "Avg Salary of last 3 months": 15453.33,
           "Avg Salary of last 6 months": 15290.5, "Avg Balance before salary of last 3 months": 113.15, "Avg Balance before salary of last 6 months": 105.22}
    
    import pandas as pd
    
    df = pd.DataFrame.from_records(dct, index=[0])
    
    df.to_csv('outputfile.csv')
    
    0 讨论(0)
提交回复
热议问题