所以我一直在尝试创建一个文件,使用我在网上找到的模板将json文件转换为csv文件。但是,我一直收到以下错误:
header = User.keys()
AttributeError: 'str'对象没有属性'keys'
# 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()
我就是不明白为什么有字符串对象而不是字典。我仔细检查了一下,User_data被存储为字典,但我仍然得到错误。
json按照以下格式组织:
{
"User" : {
"-MlIoVUgATqwtD_3AeCb" : {
"Aid" : "1",
"Gender" : "1",
"Grade" : "11",
}
}
}
for循环
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())
您正在迭代User_data
,因此User
将是["MlIoVUgATqwtD_3AeCb", ...]
。为了获得用户数据的键你应该这样索引它-
header = User_data[User].keys()