Taking API response and adding it to json, AttributeError: 'dict' object has no attribute 'append'

Question:

I am making an API request and want to add the response to a JSON. Then subsequent request responses adding to the same JSON file.

I have separated out the block of code that isn’t working, adding just one API call and dealing with the request. The issue is I cannot write the JSON file with this info. When trying I get the error "AttributeError: ‘dict’ object has no attribute ‘append’" I, therefore, presumed my result from the API request is a dictionary. I then tried, in about 4 ways, to convert this into a list to allow the append. Obviously, none of these methods worked.

import json
import requests

fname = "NewdataTest.json"

request_API = requests.get("https://api.themoviedb.org/3/movie/745?api_key=***")
print(request_API)
# Check Reponse from API
#print(request_API.json())
newData = (request_API.json())

# function to add to JSON
def write_json(data, fname):
    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
    temp.append(y)
    
write_json(data)  

JSON I am trying to add data too

[
    {
        "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
    }
]

Example of print(request_API.json())

{'adult': False, 'backdrop_path': '/paUKxrbN2ww0JeT2JtvgAuaGlPf.jpg', 'belongs_to_collection': None, 'budget': 40000000, 'genres': [{'id': 9648, 'name': 'Mystery'}, {'id': 53, 'name': 'Thriller'}, {'id': 18, 'name': 'Drama'}], 'homepage': '', 'id': 745, 'imdb_id': 'tt0167404', 'original_language': 'en', 'original_title': 'The Sixth Sense', 'overview': 'Following an unexpected tragedy, a child psychologist named Malcolm Crowe meets an nine year old boy named Cole Sear, who is hiding a dark secret.', 'popularity': 32.495, 'poster_path': '/4AfSDjjCy6T5LA1TMz0Lh2HlpRh.jpg', 'production_companies': [{'id': 158, 'logo_path': '/jSj8E9Q5D0Y59IVfYFeBnfYl1uB.png', 'name': 'Spyglass Entertainment', 'origin_country': 'US'}, {'id': 862, 'logo_path': '/udTjbqPmcTbfrihMuLtLcizDEM1.png', 'name': 'The Kennedy/Marshall Company', 'origin_country': 'US'}, {'id': 915, 'logo_path': '/4neXXpjSJDZPBGBnfWtqysB5htV.png', 'name': 'Hollywood Pictures', 'origin_country': 'US'}, {'id': 17032, 'logo_path': None, 'name': 'Barry Mendel Productions', 'origin_country': 'US'}], 'production_countries': [{'iso_3166_1': 'US', 'name': 'United States of America'}], 'release_date': '1999-08-06', 'revenue': 672806292, 'runtime': 107, 'spoken_languages': [{'english_name': 'Latin', 'iso_639_1': 'la', 'name': 'Latin'}, {'english_name': 'Spanish', 'iso_639_1': 'es', 'name': 'EspaƱol'}, {'english_name': 'English', 'iso_639_1': 'en', 'name': 'English'}], 'status': 'Released', 'tagline': 'Not every gift is a blessing.', 'title': 'The Sixth Sense', 'video': False, 'vote_average': 7.94, 'vote_count': 10125}
Asked By: Thegasman2000

||

Answers:

There are two problems with your code

  1. Your json file contains an array of objects [{...}], so data is an array of objects and data[0] is an object. What would you expect someobject.append(someotherobject) to do? You probably want to do data.append(y)

  2. You define your def write_json(data, fname): function to take two parameters. But when calling it like write_json(data) you are only passing one parameter.

The second error occured only after you have fixed the previous one. Because as long as the append was throwing an error, it didn’t even reach the write_json so it had no chance to throw an error there …

Answered By: derpirscher
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.