1

I have a JSON file that looks likes this:

{ "users":"John, admin"}

What I want is to be able to add a string into the "users" title. So, basically, I want to allow users to input a new username and add it to this list. Take the following Python code:

newUserInfo = input("Enter a new username: ")

And then say I input "Michael" Then the JSON file should look like this:

{ "users":"John, admin, Michael"}

I've tried the following:

with open(userFile, "a") as userobj:
newUserInfo = json.dump(allUserInfo["users": newUserInfo], userobj)

And It returns an error. Is there an easy way to do this?

Thanks in advance.

2
  • You are aware that {"users": ["John", "admin"]} would be a much besser format? Commented Oct 20, 2018 at 4:44
  • I am now. Thanks for the advice Commented Oct 20, 2018 at 5:10

1 Answer 1

1

Append the name to the string:

import json
s = '''{"users":"John, admin"}'''
data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'] += ', ' + newUserInfo
s2 = json.dumps(data)
print(s2)

Output:

{"users": "John, admin, Michael"}

But a more natural way to use JSON would be represent the names in a list:

import json

s = '''{"users":["John","admin"]}'''

data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'].append(newUserInfo)
s2 = json.dumps(data)
print(s2)

Output:

{"users": ["John", "admin", "Michael"]}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks for your help!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.