0

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)
3
  • This isn't valid JSON. You should've dumped str(ConfigStr) instead. Also, notice that ConfigStr is a dictionary, not a string, so the name is misleading. Commented Jun 9, 2017 at 16:04
  • Why are you attempting to just.dump() a Python representation of ConfigStr, just pass the dict to json.dump() as it is. Commented Jun 9, 2017 at 16:07
  • json.dump(config, open(configPath, 'w')) Commented Jun 9, 2017 at 16:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the quick reply worked a treat, i'm very new to python to its a bit of a learning curve

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.