使用Python将JSON解析为CSV - AttributeError:'str'对象没有属性'keys'

时间:2016-07-31 04:55:25

标签: python json csv

这个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"}}}'

感谢您对此有任何指示。

1 个答案:

答案 0 :(得分:0)

问题是您的代码希望JSON密钥是数组。这个循环在这里:

https://fcm.googleapis.com/fcm/send

期望每个顶级JSON密钥可迭代(loopable)。在原始JSON上,键for emp in emp_data: 映射到列表:

info

但是,第二个JSON示例中的“信息”键不会映射到列表,而是映射到字典:

[{"employee_name": "James", "email (...)

"info": {"arch": "x86_64","platform": "linux"} 键更改为列表会修复它:

info

更深入地说,您的"info": [{"arch": "x86_64","platform": "linux"}] 变量如下所示:

emp_data

因此,当您对其进行迭代({'platform': 'linux', 'arch': 'x86_64'} )时,for emp in emp_data将为emp"arch",您无法从中获取"platform"