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

Publish date: 2024-05-21

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

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobG5pYWd%2BcoSOqbCtoJ%2BjeqLA06ugm62kmrKzvs6rZJ2hk6l6sK7JnpqtZZiWwG66zmaYrayinq%2B2wMRmqZ6onJawpg%3D%3D