【问题标题】:JSON Single Line Parse to Multi-Line CSV with Python使用 Python 将 JSON 单行解析为多行 CSV
【发布时间】:2017-04-30 12:44:09
【问题描述】:

我是一个 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

【问题讨论】:

  • 你的问题是什么?
  • 查看 Python 文档中的 DictWriter 类。将 JSON 转换为 csv 会更简单。
  • json 代码更能解决你的问题
  • John Zwinck - 我应该在我的帖子中更清楚,我正在尝试填充一个多行 CSV 文件,而不是我现在得到的一行,并且只填充 4 列JSON 文件。
  • 这是一个格式错误的 JSON。有多个带有字符串和 int 条目的名称字段。

标签: python json csv plaid


【解决方案1】:

我认为您使 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)

【讨论】:

  • 感谢@2ps 和 thalesmello。代码经过一些小的修改后运行良好。我查看了建议的文档,我发现这些文档很有帮助(尽管我并没有完全做到这一点)。我非常感谢大家的帮助。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 2010-11-08
  • 2021-07-04
  • 1970-01-01
相关资源
最近更新 更多