【发布时间】:2022-11-17 11:46:04
【问题描述】:
我需要使用 Python 来解析 JSON 文件的帮助。我使用了一个 API 来获取特定州的立法者列表,我想遍历并找到一个特定的立法者(给定姓氏)。然后我想提取他们的 CID。该文件看起来像这样 `
{
"response": {
"legislator": [
{
"@attributes": {
"cid": "N00029147",
"firstlast": "Andy Harris",
"lastname": "Harris",
"party": "R",
"office": "MD01",
"gender": "M",
"first_elected": "2010",
"exit_code": "0",
"comments": "",
"phone": "202-225-5311",
"fax": "202-225-0254",
"website": "http://harris.house.gov",
"webform": "https://harris.house.gov/contact-me/email-me",
"congress_office": "1533 Longworth House Office Building",
"bioguide_id": "H001052",
"votesmart_id": "19157",
"feccandid": "H8MD01094",
"twitter_id": "RepAndyHarrisMD",
"youtube_url": "https://youtube.com/RepAndyHarris",
"facebook_id": "AndyHarrisMD",
"birthdate": "1957-01-25"
}
},
{
"@attributes": {
"cid": "N00025482",
"firstlast": "Dutch Ruppersberger",
"lastname": "Ruppersberger",
"party": "D",
"office": "MD02",
"gender": "M",
"first_elected": "2002",
"exit_code": "0",
"comments": "",
"phone": "202-225-3061",
"fax": "202-225-3094",
"website": "http://ruppersberger.house.gov",
"webform": "http://ruppersberger.house.gov/contact-dutch/email-dutch",
"congress_office": "2416 Rayburn House Office Building",
"bioguide_id": "R000576",
"votesmart_id": "36130",
"feccandid": "H2MD02160",
"twitter_id": "Call_Me_Dutch",
"youtube_url": "https://youtube.com/ruppersberger",
"facebook_id": "184756771570504",
"birthdate": "1946-01-31"
}
}
`
我试图制作一个 for 循环来解析这些值,但它不起作用。 (BTW finance info 是 API 给出的数据)。 `
finance_response_info = json.loads(financeInfo)
for v in finance_response_info["response"]:
for a in finance_response_info["legislator"]:
for b in finance_response_info["@attributes"][0]:
if (b["lastname"] == lastName):
candidateID = b["cid"]
`
但是,这不起作用,我不断收到错误。我怎样才能正确解析这个?
【问题讨论】: