【发布时间】:2015-12-04 17:36:12
【问题描述】:
我正在尝试从 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
}
}
}
}
}
谢谢。
【问题讨论】:
-
发布文件中的内容,即示例文件内容
-
@SIslam 我已经用 JSON 文件的内容更新了问题,抱歉。
-
你能澄清一下你想在第二个文件(ofile_name)中写什么吗? - 只是导演的名字?您正在尝试以错误的方式构建字典(my_dict)。
-
@SIslam 在 ofile_name 文件中我想要一份董事名单。所以就我而言,它只是“Alfonson Cuaron”和“Woody Allen”。 (第二个文件是一个.txt文件)