c.e.horton
c.e.horton

Reputation: 33

Why can't I use json.dump and json.loads back to back?

Why does this code produce a string (where txt_file.txt contains a dictionary placed there with json.dump()):

import json

f = open("txt_file.txt", "r+")
print(json.loads(f.read()))

But this produces an error:

import json

f = open("txt_file.txt", "r+")

dict = {
  "name": "John",
  "age": 30,
}

json.dump(dict, f) 

print(json.loads(f.read()))

I get an error thrown by the last line:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When I check the txt_file.txt, it is updated, so there was no issue with the json.dump().

Upvotes: 3

Views: 1006

Answers (1)

lenik
lenik

Reputation: 23538

You should try this, properly opening and closing the files:

import json

data = {   # `dict` is a bad name
  "name": "John",
  "age": 30,
}

with open("txt_file.txt", 'w') as fout :
    json.dump(data, fout) 

with open("txt_file.txt") as fin :
    print(json.loads(fin.read()))

Upvotes: 2

Related Questions