我有一个用 python 为我编写的代码 json2csv 文件(我命名为 json2csv.py)。
import sys, json, csv
input = open(sys.argv[1])
json_array = json.load(input)
input.close()
item_data = json_array["items"]
if len(item_data) >= 1:
first_item_id = item_data[0].keys()[0]
columns = item_data[0][first_item_id].keys()
csv_file = open(sys.argv[2], "wb")
writer = csv.writer(csv_file)
# there is currently a known bug where column names are partially uppercase, this will be fixed soon. the "map(lambda x: x.lower(), columns)" fixes this issue in the mean time
writer.writerow(map(lambda x: x.lower(), columns))
# here .items() is a standard python function
for item_id, item_data in item_data[0].items():
row = []
for column_name in columns:
if column_name.lower() == 'name_part': # lower required due to above issue
row.append(" ".join(item_data[column_name]))
else:
row.append(item_data[column_name])
writer.writerow(row)
csv_file.close()
我的输入存储在文件 pd.json 中。pd.json 的内容是
{"status": "ok", "items": [{"work_phone_extension": null, "name_part": ["PATIENT", "TEST"], "residential_street_address_line_2": "", "referring_physician_first_name": "", "residential_street_address_line_1": "", "work_phone": "", "referring_physician_last_name": "", "residential_postal_or_zip_code": "", "referring_physician_code": "", "residence_phone": "416-", "health_card": "", "item_id": 1, "unique_vendor_id_sequence": 1, "cell_phone": null, "residential_city": "Toronto", "health_card_version": "", "residential_country_and_province_or_state": "CA_ON"}, {"work_phone_extension": null, "name_part": ["STEVE", "TEST"], "residential_street_address_line_2": "", "referring_physician_first_name": "Adam", "residential_street_address_line_1": "123 Fake St", "work_phone": "", "referring_physician_last_name": "Test", "residential_postal_or_zip_code": "M5E1Z8", "referring_physician_code": "123456", "residence_phone": "416-555-5555", "health_card": "", "item_id": 2, "unique_vendor_id_sequence": 2, "cell_phone": null, "residential_city": "Toronto", "health_card_version": "", "residential_country_and_province_or_state": "CA_ON"}]}
我正在执行命令
c:\python27\python.exe c:\Python27\Scripts\json2csv.py c:\Python27\Scripts\pd.json c:\Python27\Scripts\pd.txt
我不断收到错误
'Nonetype' object has no attribute keys.
有人可以在 first_item_id = item_data[0].keys()[0] 行指出 json2csv 中的错误吗
我厌倦了坐着处理这段代码。
此代码采用 pd.json 并将文件输出为 pd.txt