[英]Extracting values from JSON file Python Error
我正在尝试从JSON文件提取某些值。 这是我的代码。
ifile = open(ifile_name, 'r')
json_decode=json.load(ifile)
result = []
for item in json_decode:
my_dict={}
my_dict['Culture']['Movies']['2014']['Gravity']= item.get('Director')
my_dict['Culture']['Movies']['2014']['Blue Jasmine'] = item.get('Director')
print my_dict
result.append(my_dict)
back_jason=json.dumps(result, ofile)
with open(ofile_name, "w+") as file :
file.write(back_jason)
我试图提取2014年导演电影的导演的名字。但是,当我运行上述代码时,出现以下错误。
my_dict['Culture']['Movies']['2014']['Gravity']= item.get('Director')
AttributeError: 'unicode' object has no attribute 'get'
谁能解释为什么我从代码中得到此错误?
这是JSON文件
{
"Culture": {
"Movies": {
"2015": {
"Birdman": {
"Genre": "Comedy",
"Director": "Alejandro Inarritu",
"Oscars": 9,
"Actors": [
"Michael Keaton",
"Enma Stone",
"Edward Norton",
"Naomi Watts"
]
},
"The Imitation Game": {
"Genre": "Drama",
"Director": "Morten Tyldum",
"Oscars": 8,
"Actors": [
"Benedict Cumberbatch",
"Keira Knightley",
"Matthew Goode"
]
},
"Magic in the Moonlight": {
"Genre": "Comedy",
"Director": "Woody Allen",
"Oscars": 0,
"Actors": [
"Enma Stone",
"Colin Firth",
"Marcia Harden"
]
}
},
"2014": {
"Gravity": {
"Genre": "Drama",
"Director": "Alfonso Cuaron",
"Oscars": 10,
"Actors": [
"Sandra Bullock",
"George Clooney",
"Ed Harris",
"Paul Sharma"
]
},
"Blue Jasmine": {
"Genre": "Comedy",
"Director": "Woody Allen",
"Oscars": 1,
"Actors": [
"Cate Blanchett",
"Sally Hawkins",
"Alec Baldwin"
]
},
"Blended": {
"Genre": "Romance",
"Director": "Frank Coraci",
"Oscars": 0,
"Actors": [
"Adam Sandler",
"Drew Barrymore",
"Jack Giarraputo"
]
},
"Ocho Apellidos Vascos": {
"Genre": "Comedy",
"Director": "Emilio Lazaro",
"Oscars": 0,
"Actors": [
"Dani Rovira",
"Clara Lago",
"Karra Elejalde",
"Carmen Machi"
]
}
}
},
"Books": {
"2015": {
"Go Set a Watchman": {
"Genre": "Fiction",
"Author": "Harper Lee",
"Pages": 278
},
"The Girl on the Train": {
"Genre": "Thriller",
"Author": "Paula Hawkins",
"Pages": 320
}
},
"2014": {
"El Barco de los Ninos": {
"Genre": "Children",
"Author": "Mario Llosa",
"Pages": 96
},
"Sapiens": {
"Genre": "History",
"Author": "Yuval Harari",
"Pages": 464
}
}
}
}
}
谢谢。
尝试仅将迭代器作为字典的键-
import json
ifile = open(r"D:\tst.txt", 'r')
json_decode=json.load(ifile)
result = []
for i in json_decode['Culture']['Movies']['2014']:
data = json_decode['Culture']['Movies']['2014'][i]['Director']
print data
result.append(data)
with open(r"D:\tst1.txt", "w+") as file :
for j in result:
file.write(j+'\n')
输出文件内容
Frank Coraci
Emilio Lazaro
Woody Allen
Alfonso Cuaron
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.