Teleshot
Teleshot

Reputation: 75

Correct way of loading JSON from file into a Python dictionary

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?

Upvotes: 6

Views: 8863

Answers (3)

Yuwen Yan
Yuwen Yan

Reputation: 4935

Your current method is correct here. For json.loads() and ast.literal_eval(), they are parsing entirely different languages. If your json file is exactly the content you pasted here, I recommend using the json library as it's faster.

https://stackoverflow.com/a/21223411/456105

Upvotes: 0

trueter
trueter

Reputation: 199

Disclaimer: I don't know if this is the definite correct way, but it works for me:

jd0 = {
   'foo': 1337,
   'bar': 'baz'
}
# Dump it somewhere
with open('/Dump/it/somewhere/test.json', 'w') as fh: 
    json.dump(jd0, fh)

If I then load it, its a dict again:

with open('/Dump/it/somewhere/test.json', 'r') as fh:
    jd1 = json.load(fh)
    print type(jd1) == dict

Prints

 True

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

Your data must have already been a JSON string to begin with and then you double-encoded it during the json.dump. Then of course you need to double-decode it later. So instead of encoding the original JSON with JSON again, just write it to the file as-is:

with open(filename, 'w+') as f:
    f.write(data)

Upvotes: 7

Related Questions