Python获取API响应并添加到JSON键错误

qacovj5a  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(144)

我有一个脚本,它从JSON文件中获取一个ID,并将其添加到API请求的URL中,目的是让一个循环遍历大约1000个ID,并生成一个包含所有信息的JSON文件。
当前代码调用第一个请求并创建和填充JSON文件,但是在循环中运行时会抛出一个键错误。

import json
import requests

fname = "NewdataTest.json"

def write_json(data, fname):
    fname = "NewdataTest.json"
    with open(fname, "w") as f:
        json.dump(data, f, indent = 4)
    with open (fname) as json_file:
        data = json.load(json_file)
        temp = data[0]
            #print(newData) 
        y = newData
        data.append(y)

# Read test.json to get tmdb IDs 
tmdb_ids = []
with open('test.json', 'r') as json_fp:
    imdb_info = json.load(json_fp)

tmdb_ids = [movie_info['tmdb_id'] for movies_chunk in imdb_info for movie_index, movie_info in movies_chunk.items()]
# Add IDs to API call URL
for tmdb_id in tmdb_ids:
    print("https://api.themoviedb.org/3/movie/" + str(tmdb_id) + "?api_key=****")
    # Send API Call
    response_API = requests.get("https://api.themoviedb.org/3/movie/" + str(tmdb_id) + "?api_key=****")
    # Check API Call Status
    print(response_API.status_code)
    write_json((response_API.json()), "NewdataTest.json")

错误出现在“temp = data[0]”这一行,我试着打印数据的键,但一无所获。此时,我不知道我在做什么,因为我已经破解了它,它几乎不像一段内聚的代码。我的目标是创建一个简单的函数来从JSON中获取数据,一个生成API调用URL,一个将结果写入新的JSON。
API响应JSON示例:

{
    "adult": false,
    "backdrop_path": "/e1cC9muSRtAHVtF5GJtKAfATYIT.jpg",
    "belongs_to_collection": null,
    "budget": 0,
    "genres": [
        {
            "id": 10749,
            "name": "Romance"
        },
        {
            "id": 35,
            "name": "Comedy"
        }
    ],
    "homepage": "",
    "id": 1063242,
    "imdb_id": "tt24640474",
    "original_language": "fr",
    "original_title": "Disconnect: The Wedding Planner",
    "overview": "After falling victim to a scam, a desperate man races the clock as he attempts to plan a luxurious destination wedding for an important investor.",
    "popularity": 34.201,
    "poster_path": "/tGmCxGkVMOqig2TrbXAsE9dOVvX.jpg",
    "production_companies": [],
    "production_countries": [
        {
            "iso_3166_1": "KE",
            "name": "Kenya"
        },
        {
            "iso_3166_1": "NG",
            "name": "Nigeria"
        }
    ],
    "release_date": "2023-01-13",
    "revenue": 0,
    "runtime": 107,
    "spoken_languages": [
        {
            "english_name": "English",
            "iso_639_1": "en",
            "name": "English"
        },
        {
            "english_name": "Afrikaans",
            "iso_639_1": "af",
            "name": "Afrikaans"
        }
    ],
    "status": "Released",
    "tagline": "",
    "title": "Disconnect: The Wedding Planner",
    "video": false,
    "vote_average": 5.8,
    "vote_count": 3
}
rt4zxlrg

rt4zxlrg1#

您可以将API调用的所有结果存储到一个列表中,然后将此列表以Json格式保存到文件中。例如:

#...

all_data = []

for tmdb_id in tmdb_ids:
    print("https://api.themoviedb.org/3/movie/" + str(tmdb_id) + "?api_key=****")
    # Send API Call
    response_API = requests.get("https://api.themoviedb.org/3/movie/" + str(tmdb_id) + "?api_key=****")

    # Check API Call Status
    print(response_API.status_code)

    if response_API.status_code == 200:
        # store the Json data in a list:
        all_data.append(response_API.json())

# write the list to file
with open('output.json', 'w') as f_out:
    json.dump(all_data, f_out, indent=4)

这将生成output.json,其中所有响应都是Json格式。

相关问题