Joshua Robertson
Joshua Robertson

Reputation: 15

Error while updating .txt file containing JSON with Python

Currently learning to use JSON data structures with python, have been able to read in files and write files but am having some issues with updating an existing file, getting the error: 'str' object has no attribute 'update'. I have searched and tried the solutions others have suggested but have had no luck in fixing this. Below is my code, the idea is that it adds a new user/password to the existing file.

import json

sUser_Login = {}
user = input('Create Username: >> ')
passw = input('Create Password: >> ')

sUser_Login[user] = passw


with open('JSONData.txt', 'r') as f:
    data = json.load(f)

data.update(sUser_Login)


with open('JSONData.txt', 'w')as f:
    json.dump(data, f)

Appreciate any assistance. Thanks Again

EDIT: Here is the data in the JSONData.txt file:

"{\"Jrob\": \"abc123\", \"jrobertson\": \"123abc\"}"

Upvotes: 1

Views: 43

Answers (1)

Russel Simmons
Russel Simmons

Reputation: 361

Your code is actually fine, as long as you first create the file JSONData.txt containing just {}, an empty dictionary (or "object" in JSON terminology). It looks like when you are running it, JSONData.txt contains a JSON string? Then data ends up as a string, and a string doesn't have an update() method hence the error.

Upvotes: 1

Related Questions