【问题标题】:How do I loop through an entire JSON file and extract the data into variables如何遍历整个 JSON 文件并将数据提取到变量中
【发布时间】:2018-07-27 22:32:17
【问题描述】:

我正在处理一个 python 文件,该文件从 JSON 文件中提取电影及其详细信息,然后将数据保存到自定义电影对象中。现在,我可以从庞大的列表中选择一部电影。

但是,我希望能够遍历并获取每个流派、导演、演员,并将它们添加到单独的数组中。现在当我尝试这样做时,我得到了这个错误:

    Traceback (most recent call last):
  File "/Users/leoconnelly/PycharmProjects/MLFinal/tester.py", line 27, in <module>
    tempGenre = (contents['results'][i]['genre'])
TypeError: list indices must be integers or slices, not str

我还想创建一个包含标题、演员、导演和类型的自定义电影对象的数组。

我的代码如下所示:

from movie import Movie
from user import User
import json
from pprint import pprint


movieArray = []
nameArray = []
directorArray =  []
genreArray = []
##actorArray = []

movieToBeInputted = Movie("","","","")


with open('movies.json') as f:
    contents = json.load(f)
    print(contents['results'][600]['title'])
    movieToBeInputted.name = (contents['results'][600]['title'])
    movieToBeInputted.director = (contents['results'][600]['director'])
    movieToBeInputted.genre = (contents['results'][600]['genre'])
    movieToBeInputted.actors = (contents['results'][600]['cast'])
    movieArray.append(movieToBeInputted)


for i in contents:
    tempGenre = (contents['results'][i]['genre'])
    genreArray.append(tempGenre) #this is where the error happens

    print("xxxxxxx")
    print(movieToBeInputted.actors)




##d = json.load(json_data)

##json_movie_data = json.dumps(json_data)




##movieToBeInputted.actors = json_movie_data

这是我的 json 数据:

{
  "results": [
    {
      "title": "After Dark in Central Park",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Boarding School Girls' Pajama Parade",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Buffalo Bill's Wild West Parad",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Caught",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Clowns Spinning Hats",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Capture of Boer Battery by British",
      "year": 1900,
      "director": "James H. White",
      "cast": null,
      "genre": "Short documentary",
      "notes": null
    },
    {
      "title": "The Enchanted Drawing",
      "year": 1900,
      "director": "J. Stuart Blackton",
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Family Troubles",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "Feeding Sea Lions",
      "year": 1900,
      "director": null,
      "cast": "Paul Boyton",
      "genre": null,
      "notes": null
    },
    {
      "title": "How to Make a Fat Wife Out of Two Lean Ones",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": "Comedy",
      "notes": null
    },
    {
      "title": "New Life Rescue",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    },
    {
      "title": "New Morning Bath",
      "year": 1900,
      "director": null,
      "cast": null,
      "genre": null,
      "notes": null
    }
  ]
}

【问题讨论】:

  • contents 是一本字典...你希望 for i in contents 是什么?

标签: python json


【解决方案1】:

您需要for i in range(len(content['results'])),然后content['results'][i] 将作为list indices <b>must be integers</b> 工作

当您执行for i in content 时,您正在循环内容字典的键,它们是字符串。


但是,contents['results'] 是一个列表。您可以将它们作为完整对象循环,而不是获取特定的数字索引。

这使用列表推导从结果列表中获取电影对象的完整列表。

with open('movies.json') as f:
    contents = json.load(f)
    results = contents.get('results', [])
    movies = [ 
       Movie(
           r.get('title'),
           r.get('director'),
           r.get('genre'),
           r.get('cast')
       ) for r in results ]
    for m in movies:
        print(m.name)

我希望能够遍历并获取每个流派、导演、演员并将它们添加到单独的数组中

您可以从您制作的电影数组中执行类似操作。

这将通过将set 对象放入列表来返回所有电影的唯一导演。

directors = list(set(m.director for m in movies if m.director is not None))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多