I am currently doing this to save JSON to a file:
with open(filename, 'w+') as f:
json.dump(data, f)
and I am doing this to load JSON from a file into a Python dictionary:
with open(filename, 'r') as f:
data = json.loads(json.load(f))
I understand that json.load
loads JSON from a file and json.loads
loads JSON from a string.
When I call json.load(f)
to load the JSON from file I get a string representation of the JSON object:
'{"a": 1,"b": 2,"c": 3}'
I then call json.loads(json.load(f))
to convert that string representation to a Python dictionary:
{'a': 1, 'b': 2, 'c': 3}
I understand that I can also use ast.literal_eval()
to convert the string into a Python dictionary.
My question is - what is the correct way of loading JSON from a file directory into a Python dictionary? is it really necessary to call both json.loads
and json.load
to get JSON from a file into a dictionary?