1

私は Python 初心者で、銀行取引を取得するために Plaid API を使用しています。各トランザクションを独自の行にしたいのですが、レコードごとに 4 つの値 (date、_account、name、amount) のみを取得し、そのデータを 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ファイル

4

1 に答える 1

2

この過度に複雑で紛らわしい JSON を CSV で作成していると思います。クラスの使用で私を打ち負かした@thalesmalloへの帽子のヒントDictWriter。これを試して:

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)
于 2016-12-15T05:11:49.227 に答える