Lou Lou - 4 months ago 48
JSON Question

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": "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()


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.

Answer

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.

Comments