JSON 使用 Python 将单行解析为多行 CSV

JSON Single Line Parse to Multi-Line CSV with Python

我是一个 Python 菜鸟,正在使用 Plaid API 进行银行交易。我希望每笔交易都是它自己的行,我只想为每条记录提取四个值:日期、_account、名称和金额,并用该数据填充一个 CSV 文件。我有以下代码填充单行 CSV(JSON 文件也已附加)。就谷歌搜索后如何执行此操作的示例而言,我似乎无法弄清楚我在寻找什么。非常感谢任何帮助。

import csv

#Configuration
from plaid import Client

Client.config({
    'url': 'https://api.plaid.com'
})

#Connect to Plaid
from plaid import Client
from plaid import errors as plaid_errors
from plaid.utils import json

client = Client(client_id='test_id', secret='test_secret')
account_type = 'suntrust'

try:
    response = client.connect(account_type, {
    'username': 'plaid_test',
    'password': 'plaid_good'
    })
except plaid_errors.PlaidError:
     pass
else:
    connect_data = response.json()

#Get transactions from Plaid
response = client.connect_get()
transactions = response.json()

#Save the transactions JSON response to a csv file in the Python Projects directory
with open('transactions.csv', 'w') as outfile:
    json.dump(transactions, outfile)

csvfile = open('transactions.csv', 'r')
jsonfile = open('transactions.json', 'w')

fieldnames = ("date", "_account","name","amount")
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

JSON FILE

我认为您使用 CSV 使这个变得过于复杂和混淆 JSON。向@thalesmallo 致敬,他在使用 DictWriter class 时抢先一步打败了我。试试这个:

import csv
from plaid import Client

Client.config({
    'url': 'https://api.plaid.com'
})

#Connect to Plaid
from plaid import Client
from plaid import errors as plaid_errors
from plaid.utils import json

client = Client(client_id='test_id', secret='test_secret')
account_type = 'suntrust'

try:
    response = client.connect(account_type, {
        'username': 'plaid_test',
        'password': 'plaid_good'
    })
except plaid_errors.PlaidError:
     pass
else:
    connect_data = response.json()
response = client.connect_get()
data = response.json()
transactions = data['transactions'] # see https://plaid.com/docs/api/#data-overview

#Save the transactions JSON response to a csv file in the Python Projects directory
header = ("date", "_account", "name", "amount")
with open('transactions.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=header, extrasaction='ignore')
    writer.writeheader()
    for x in transactions:
        writer.writerow(x)