如何在python中将json转换为csv

时间:2019-01-02 06:19:48

标签: python json python-3.x csv

以下是我的json文件输入

{"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}

代码

    with open('/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.json', "r") as f:
        BankData = json.loads(f.read())
    x = json.loads(json.dumps(BankData))
    f = csv.writer(open("/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.csv", "w"))
    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"])

    for y in x:
        f.writerow([x["userID"], x["Is salary credited before 5th"],
                    x["Avg Salary of last 3 months"],
                    x["Avg Salary of last 6 months"],
                    x["Avg Balance before salary of last 3 months"],
                    x["Avg Balance before salary of last 6 months"]])

输出

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
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22

所以,我确实得到了答案,但没有打印一次,而是打印了7次。如何解决此问题。

4 个答案:

答案 0 :(得分:3)

您还可以使用熊猫来处理数据框,

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')

答案 1 :(得分:1)

您可以执行以下操作:通过导入jsoncsv模块来读取JSON并写入CSV文件

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())

答案 2 :(得分:0)

BankData是您不需要对其进行迭代的命令。您可以使用键直接访问值。

例如:

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"]])

答案 3 :(得分:0)

GeekSambhu的解决方案对我进行了微小的修改。我做了一些修改,因为像Vinsent一样,我看到了 KeyError 。如果JSON结构具有一个顶级对象来保存数据行的数组,则人们可能会收到KeyError(这被认为是JSON的最佳实践)。假设有一个名为“数据”的顶级对象,则只需更改GeekSambhu解决方案的两行代码。

writer.writerow(_json ['data'] [0] .keys())#标头行
_json ['data']中的行: