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?
1 Answer 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.
answered Aug 25, 2021 at 4:15
OneCricketeer
193k20 gold badges147 silver badges277 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
"). And no, they are not the same thing. The former is the "string representation of a list" while the latter is simply a string.type(characters). Then you'll see the differenceread(), notjson.load(). Also my point was you should always post the actual output; not the output you think you're seeing.