Lou
Lou

Reputation: 5

Parsing JSON to CSV with Python - AttributeError: 'str' object has no attribute 'keys'

This JSON to CSV code example is working great:

employee_data = '{"info":[{"employee_name": "James", "email": "[email protected]", "job_profile": "Sr. Developer"},{"employee_name": "Smith", "email": "[email protected]", "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()

My trouble comes in when I'm trying to use the following JSON data below...

I get an AttributeError: 'str' object has no attribute 'keys'. Please keep your response simple as this is my 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"}}}'

Thank you for any direction on this.

Upvotes: 0

Views: 4586

Answers (1)

David Gomes
David Gomes

Reputation: 5825

The problem is that your code expects the JSON keys to be arrays. This loop here:

for emp in emp_data:

Expects each top level JSON key to be iterable (loopable). On your original JSON, the key info maps to a list:

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

However, the ìnfo` key on the second JSON example does not map to a list but instead to a dictionary:

"info": {"arch": "x86_64","platform": "linux"}

Changing the info key to a list fixes it:

"info": [{"arch": "x86_64","platform": "linux"}]

In further depth, your emp_data variable looks like this:

{'platform': 'linux', 'arch': 'x86_64'}

And so when you iterate it (for emp in emp_data), emp will be "arch" or "platform", which you cannot get .keys() from.

Upvotes: 3

Related Questions