Python - Attributeerror: 'Dict' Object Has No Attribute 'Replace'

Whenever I run the code below, I get this error:

AttributeError: 'dict' object has no attribute 'replace'

I am unsure how to fix this. I want to search the json file and find "Screenshot Package" and replace it with user input but I just get that error.

My code:

numberofscreenshots = input("How much screenshots do you want?: ")

if numberofscreenshots == "1":

    screenshoturl = input("Link to screenshot: ")

    with open('path/to/json/file','r') as f:
        data = f.read()

    data = json.loads(data)

    # Check the data before.
    print( data['tabs'][0]['views'][1]['screenshots'] )

    # Overwrite screenshots placeholders in template file if more then one.
    data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0]

    # Check after to make sure it worked.
    print( data['tabs'][0]['views'][1]['screenshots'] )

    # Now search for the screenshot option and add users input.
    screenshotplaceholdertext = {"Screenshot URL 1":screenshoturl}
    for removescreenshotplaceholders in data:
        for screenshotplaceholder, removescreenshotplaceholder in screenshotplaceholdertext.items():
            removescreenshotplaceholders = removescreenshotplaceholders.replace(screenshotplaceholder, removescreenshotplaceholder)
        data.replace(removescreenshotplaceholders)

    # Write data to JSON file.
    with open('path/to/json/file', 'w') as f:
        f.write(json.dumps(data))
else:
    print("Something went wrong.")

Any help would be nice. Thanks!

6

1 Answer

It looks like you're just trying to replace the value for key "Screenshot URL" with screeenshoturl. If so you're going about it all wrong. Try this:

with open('path/to/json/file','r') as f:
    data = json.loads(f.read())

# Check the data before.
try:
    data['tabs'][0]['views'][1]['screenshots'][0]
except ValueError:
    print("No Screenshots")

# Overwrite screenshots placeholders.
data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0]

#from the error, I'm getting that data['tabs'][0]['views'][1]['screenshots']
#is now a dict, so there should only be one "Screenshot URL" key so no need
#to do any loops here, just replace the key.
data['tabs'][0]['views'][1]['screenshots'].update({"Screenshot URL":screenshoturl})

with open('path/to/json/file', 'w') as f:
    f.write(json.dumps(data))
11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest