StuartAM
StuartAM

Reputation: 15

reading JSON stored in txt file with Python

i wand to save some config values to a text file so i can use them later on in my code, so i decided on saving it into a text file in a JSON format but when i try and read the value from the file i get an error

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

the text file content is:

"{'EditDate': 1497014759002}"

import json
import os
cPath = os.path.dirname(os.path.realpath(__file__))
configPath = cPath+'/tt.txt'
ConfigStr = {"EditDate" : 1497014759002}
print(ConfigStr)
print("-----------")
with open(configPath, 'w') as outfile:
    json.dump(repr(ConfigStr), outfile)
with open(configPath) as json_data:
    d = json.load(json_data)
    jstr = d
    print(jstr)
    print("-----------")
    a = json.loads(jstr)
    lastedit = a['EditDate']
    print(lastedit)

Upvotes: 0

Views: 2529

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

You should use json.dump to dump into the file. Pass it the object to write and a file-like object.

...


with open(configPath, 'w') as outfile:
    json.dump(ConfigStr, outfile)
with open(configPath) as json_data:
    d = json.load(json_data)

print(d)
print("-----------")

lastedit = d['EditDate']
print(lastedit)

Reference:

https://docs.python.org/2/library/json.html#json.dump

Upvotes: 2

Related Questions