6

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?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Teleshot
  • 75
  • 2
  • 7
  • 4
    I would certainly recommend using the `json` library as you did rather than `ast.literal_eval`, the former was made for exactly this purpose. – Cory Kramer Jun 05 '15 at 12:59
  • 1
    [`json.load`](https://docs.python.org/2/library/json.html#json.load) should be returning objects, not a string. What's with the extra call to `.loads`? – jonrsharpe Jun 05 '15 at 13:04

3 Answers3

7

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)
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
1

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
trueter
  • 199
  • 8
0

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

Community
  • 1
  • 1
Yuwen Yan
  • 4,777
  • 10
  • 33
  • 63