0

I uploaded data in a json file as below

import json
characters = ['Robin Hood', 'Aladdin', 'Muhammad Ali', 'Santa Claus', 'Che Guevara']
filename = 'username.json'
with open(filename, 'w') as f:
    json.dump(characters, f)

I was told not to use the read() method to read the file but instead json's load() method. The thing is when I try the both I end up with the same terminal output.

# same file
with open(filename) as f:
    characters = json.load(f)
    print('Using load():', characters)
# same file
with open(filename) as f:
    characters = f.read()
    print('Using read():', characters)

output

Using load(): ['Robin Hood', 'Aladdin', 'Muhammad Ali', 'Santa Claus', 'Che Guevara']
Using read(): ["Robin Hood", "Aladdin", "Muhammad Ali", "Santa Claus", "Che Guevara"]

Is there any difference?

5
  • 2
    Are you sure you've posted the actual output? They shouldn't look the same. The JSON one should have double quotes ("). And no, they are not the same thing. The former is the "string representation of a list" while the latter is simply a string. Commented Aug 25, 2021 at 3:52
  • It's actually the opposite I get. The latter has double quotes not the json one. Commented Aug 25, 2021 at 4:11
  • 1
    Use type(characters). Then you'll see the difference Commented Aug 25, 2021 at 4:12
  • The difference is apparent now. Superb! Commented Aug 25, 2021 at 4:14
  • @O'BrienZimeTaga Yes, by "JSON one" I meant directly printing the JSON file, so it's the one with read(), not json.load(). Also my point was you should always post the actual output; not the output you think you're seeing. Commented Aug 25, 2021 at 5:22

1 Answer 1

1

f.read() returns a string, always.

This is fine for printing purposes, but doesn't matter if the file is JSON or not.

json.load(f) will return the appropriate Python object type from the file as well as pseudo-validate the file is really JSON via parsing it.

Sign up to request clarification or add additional context in comments.

Comments

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.