1

this is my code that Im trying to get to write into a JSON file in the format {"Example1": "Example"} Im getting an error which reads:

db_file.write(json.dump({"Admin": keyPass}, db_file)) TypeError: must be str, not None

For this code:

         keyPass = input("Create Admin Password » ")                    
         with codecs.open(os.path.join(PATH), 'w') as db_file:
             db_file.write(json.dump({"Admin": keyPass}, db_file))

This is the weird part, it creates it in the file fine and how I want it to be formatted is correct, yet it still comes up with the error above.

Could anyone please help me with what I need to correct here?

1 Answer 1

4

The first two arguments to the json.dump function are:

  • obj: The object to serialize
  • fp: A file-like object to write the data to

So what's happening here, is the inner call to json.dump is successfully writing the JSON-encoded string to your file, but then you're trying to pass the output of it (which will always be None) to your fileobject's write function.

You have two options:

  1. use json.dumps(stringToEncodeAsJSON) instead of json.dump, which will return the JSON formatted string which can then be written to your file using your fileObject's write function
  2. Remove the fileObject's write function from around the json.dump call

Update:

Here are some examples of how you could do it

keyPass = input("Create Admin Password > ")

with open(pathName, 'w') as db_file:
    db_file.write(json.dumps({"Admin": keyPass}))

with open(pathName, 'w') as db_file:
    json.dump({"Admin": keyPass}, db_file)
Sign up to request clarification or add additional context in comments.

5 Comments

Whats wrong with this: with codecs.open(os.path.join(PATH), 'w') as db_file: json.dump({"Admin": keyPass})
Is that related to the original question? You're calling json.dump but not passing in the file pointer argument, which is required
I was trying to fix the problem, but I don't think I understand it.
Let me give you a few examples
Ahh, I understand the problem now.. Thank you. I guess I'm tired.. xD

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.