【发布时间】:2016-07-31 04:55:25
【问题描述】:
这个 JSON 到 CSV 代码示例运行良好:
employee_data = '{"info":[{"employee_name": "James", "email": "james@gmail.com", "job_profile": "Sr. Developer"},{"employee_name": "Smith", "email": "Smith@gmail.com", "job_profile": "Project Lead"}]}'
#This can be parsed and converted to CSV using python as shown below:
import json
import csv
employee_parsed = json.loads(employee_data)
emp_data = employee_parsed['info']
# open a file for writing
employ_data = open('Employee.csv', 'w')
# create the csv writer object
csvwriter = csv.writer(employ_data)
count = 0
for emp in emp_data:
if count == 0:
header = emp.keys()
csvwriter.writerow([header])
count += 1
csvwriter.writerow([emp.values()])
employ_data.close()
当我尝试使用以下 JSON 数据时,我遇到了麻烦...
我得到一个 AttributeError: 'str' 对象没有属性 'keys'。请保持您的回答简单,因为这是我的 Python “Hello World”。 :-)
employee_data = '{"info": {"arch": "x86_64","platform": "linux"},"packages": {"_license-1.1-py27_0.tar.bz2": {"build": "py27_0","build_number": 0,"date": "2013-03-01","depends": ["python 2.7*"],"license": "proprietary - Continuum Analytics, Inc.","license_family": "Proprietary","md5": "5b13c8cd498ce15b76371ed85278e3a4","name": "_license","requires": [],"size": 194947,"version": "1.1"}}}'
感谢您对此的任何指导。
【问题讨论】: