简体   繁体   中英

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!

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM