【发布时间】:2026-02-05 20:50:01
【问题描述】:
我正在解析来自 here 的嵌套 JSON 数据。此文件中的某些文件与多个committee_id 关联。我需要与每个文件相关的所有委员会。我不确定,但我想这意味着为每个committee_id 写一个新行。我的代码如下:
import os.path
import csv
import json
path = '/home/jayaramdas/anaconda3/Thesis/govtrack/bills109/hr'
dirs = os.listdir(path)
outputfile = open('df/h109_s_b', 'w', newline='')
outputwriter = csv.writer(outputfile)
for dir in dirs:
with open(path + "/" + dir + "/data.json", "r") as f:
data = json.load(f)
a = data['introduced_at']
b = data['bill_id']
c = data['sponsor']['thomas_id']
d = data['sponsor']['state']
e = data['sponsor']['name']
f = data['sponsor']['type']
i = data['subjects_top_term']
j = data['official_title']
if data['committees']:
g = data['committees'][0]['committee_id']
else:
g = "None"
outputwriter.writerow([a, b, c, d, e, f, g, i, j])
outputfile.close()
我遇到的问题是我的代码只收集列出的第一个committee_id。例如,文件hr145 如下所示:
"committees": [
{
"activity": [
"referral",
"in committee"
],
"committee": "House Transportation and Infrastructure",
"committee_id": "HSPW"
},
{
"activity": [
"referral"
],
"committee": "House Transportation and Infrastructure",
"committee_id": "HSPW",
"subcommittee": "Subcommittee on Economic Development, Public Buildings and Emergency Management",
"subcommittee_id": "13"
},
{
"activity": [
"referral",
"in committee"
],
"committee": "House Financial Services",
"committee_id": "HSBA"
},
{
"activity": [
"referral"
],
"committee": "House Financial Services",
"committee_id": "HSBA",
"subcommittee": "Subcommittee on Domestic and International Monetary Policy, Trade, and Technology",
"subcommittee_id": "19"
}
这是有点棘手的地方,因为当法案通过小组委员会时,我还希望 subcommittee_id 与 committee_id 相关联:
bill_iid committee subcommittee introduced at Thomas_id state name
hr145-109 HSPW na "2005-01-4" 73 NY "McHugh, John M."
hr145-109 HSPW 13 "2005-01-4" 73 NY "McHugh, John M."
hr145-109 HSBA na "2005-01-4" 73 NY "McHugh, John M."
hr145-109 HSBA 19 "2005-01-4" 73 NY "McHugh, John M."
有什么想法吗?
【问题讨论】:
标签: python json pandas dataframe