So I have been attempting to create a file to convert json files to csv files using a template i found online. However, I keep receiving the following error:
header = User.keys()
AttributeError: 'str' object has no attribute 'keys'
Here is the code I'm using:
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('/Users/jhillier5/Downloads/mentalhealthcheck-in-default-rtdb-export (1).json') as json_file:
data = json.load(json_file)
User_data = data['User']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
print(User_data)
print(type(User_data))
for User in User_data:
if count == 0:
# Writing headers of CSV file
header = User.keys()
csv_writer.writerow(header)
count = 1
# Writing data of CSV file
csv_writer.writerow(User.values())
data_file.close()
I simply don't understand why there is a string object and not a dict. I double checked and User_data is stored as a dict but i still get the error.
The json is organised in the following format:
{
"User" : {
"-MlIoVUgATqwtD_3AeCb" : {
"Aid" : "1",
"Gender" : "1",
"Grade" : "11",
}
}
}
CodePudding user response:
In this for loop
for User in User_data:
if count == 0:
# Writing headers of CSV file
header = User.keys()
csv_writer.writerow(header)
count = 1
# Writing data of CSV file
csv_writer.writerow(User.values())
You are iterating through User_data
, so User
will be ["MlIoVUgATqwtD_3AeCb", ...]
. In order to get the keys of that user data you should index it this way -
header = User_data[User].keys()