【问题标题】:Exporting JSON API result into CSV file (Vertically AND with Header)将 JSON API 结果导出到 CSV 文件(垂直与标题)
【发布时间】:2018-10-27 18:27:21
【问题描述】:

我正在尝试将 JSON API 结果导出为格式正确的 CSV。

注意:SmartMover API 可以通过输入个人地址、名字、姓氏等来帮助确定个人地址是否是最新的。

以下是我的 JSON 格式的 API 结果。

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=', '记录': [{'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', 'DeliveryIndi​​cator': '', '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', “传输结果”:“”,“版本”:“4.0.4.48”} 【2.6s完成】

从这个结果中,我想在 AddressLine2 标头中提取 4 个输出值。 (我在 API 中输入了 4 个值)例如,

'Records':........'AddressLine2':'1009 W MONROE ST',............

所以我编写了以下 Python 查询:

r = response.json()

df = pd.read_csv(r"C:\users\testu\documents\travis_test.csv",delimiter = ',',na_values="nan")

with open(r'C:\users\testu\documents\travis3.csv', 'w+') as f:
    cf = csv.writer(f)
    cf.writerow(r['Records'][0]['AddressLine2'].split(','))

print(r['Records'][0]['AddressLine2'].split(','))

但是,它只提取没有 Header AND 水平的值,如下图所示:

如何使用 Header (AddressLine2) AND 垂直提取值?

感谢您的帮助!

【问题讨论】:

    标签: python json api csv


    【解决方案1】:

    我最近不得不做类似的事情。不过我最终使用了不同的方法,并没有使用 Pandas。

    我假设您使用的是 python requests 库、csv 库、pandas 和 python 3。

    假设您只尝试获取带有标题 AddressLine2 的一列,那么这样的事情应该可以工作:

    import requests
    import unicodedata
    import csv
    
    url = "The API endpoint"
    
    # Build an array to contain the Address values. Add the header AddressLine2
    # by appending the string to output_1.
    output_1 = []
    output_1.append("AddressLine2")
    
    # Get the information from the API using requests.
    response = requests.get(url)
    data = response.json()
    
    # Collect only Address Line 2 from the JSON output. properly encode/decode the 
    # string and add it to output_1. 
    for record in data['records']:
        addressline2 = record['addressline2']
        decode_1 = unicodedata.normalize('NFKD', addressline2)
        output_1.append(decode_1)
    
    # Write the values to a column
    with open(csvfile, 'w') as fp:
        writer = csv.writer(fp, dialect = 'excel')
        for val in output_1:
            writer.writerow([val])
    

    我意识到我没有为此使用熊猫。因此,如果您需要该 pandas 数据框进行其他计算,这可能是太多额外的工作。但是,如果不是,那么这有望为您提供该专栏!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2018-03-22
      • 2017-12-31
      相关资源
      最近更新 更多