将JSON API结果导出到CSV fi

2024-05-15 00:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将JSON API结果导出到CSV文件中。我有一个CSV格式的问题。在

JSON API结果

{'CASSReportLink': 'https://smartmover.melissadata.net/v3/Reports/CASSReport.aspx?tkenrpt=YvBDs39g52jKhLJyl5RgHKpuj5HwDMe1pE2lcQrczqRiG3/3y5yMlixj5S7lIvLJpDyAOkD8fE8vDCg56s3UogNuAkdTbS2aqoYF5FvyovUjnXzoQaHaL8TaQbwyCQ2RB7tIlszGy5+LqFnI7Xdr6sjYX93FDkSGei6Omck5OF4=', 'NCOAReportLink': 'https://smartmover.melissadata.net/v3/Reports/NCOAReport.aspx?tkenrpt=8anQa424W7NYg8ueROFirapuj5HwDMe1pE2lcQrczqRiG3/3y5yMlixj5S7lIvLJpDyAOkD8fE8vDCg56s3UogNuAkdTbS2aqoYF5FvyovUjnXzoQaHaL8TaQbwyCQ2RB7tIlszGy5+LqFnI7Xdr6sjYX93FDkSGei6Omck5OF4=', 'Records': [{'AddressExtras': '', 'AddressKey': '78704,78704', 'AddressLine1': ' , , ,STE C-100 ', 'AddressLine2': '1009 W MONROE ST ,1600 S 5TH ST ,1008 W MILTON ST ,3939 BEE CAVES RD ', 'AddressTypeCode': '', 'BaseMelissaAddressKey': '', 'CarrierRoute': '', 'City': 'Austin ,Austin ,Austin ,Austin ', 'CityAbbreviation': 'Austin ,Austin ,Austin ,Austin ', 'CompanyName': '', 'CountryCode': 'US', 'CountryName': 'United States', 'DeliveryIndicator': '', 'DeliveryPointCheckDigit': '', 'DeliveryPointCode': '', 'MelissaAddressKey': '', 'MoveEffectiveDate': '', 'MoveTypeCode': '', 'PostalCode': '78704,78704,78704,78746', 'RecordID': '1', 'Results': 'AE07', 'State': '', 'StateName': 'TX ,TX ,TX ,TX ', 'Urbanization': ''}], 'TotalRecords': '1', 'TransmissionReference': '1353', 'TransmissionResults': '', 'Version': '4.0.4.48'} [Finished in 2.6s]

Python查询

r = response.json()


output_1 = []
output_1.append("AddressLine2")

# Collect only Address Line 2 from the JSON output. properly encode/decode the string and add it to output_1. 
for record in r['Records']:
    addressline2 = record['AddressLine2']
    addressline2.split(",")
    print(addressline2)
    output_1.append(addressline2)

print(output_1)

# Write the values to a column
with open(r"C:\users\testu\documents\travis_output.csv", 'w') as fp:
    writer = csv.writer(fp, dialect = 'excel')
    for val in output_1:
        writer.writerow([val])

结果我得到了

enter image description here

我想要的结果

enter image description here

我认为addressline2.split(“,”)应该可以完成它的工作,但是它没有工作。谢谢你的帮助!在


Tags: csvtheinhttpsapijsonoutputwriter
2条回答

您正在运行addressline2.split(","),但您没有在CSV中使用该操作的输出,而是再次使用addressline2split method创建一个新变量作为函数的输出,它不将原始变量转换为列表。在

你需要捕捉输出,例如

output_1.append(addressline2.split(","))

这会给你一个结果:

output_1 += addressline2.split(",") 

相关问题 更多 >

    热门问题