用Python读取txt文件中存储的JSON

2024-10-04 05:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一些配置值保存到一个文本文件中,以便以后在代码中使用它们,所以我决定以JSON格式将其保存到一个文本文件中,但是当我试图从文件中读取值时,我遇到了一个错误

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

文本文件内容为:

"{'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)

Tags: pathimportjsonosaswithopenoutfile
1条回答
网友
1楼 · 发布于 2024-10-04 05:34:24

您应该使用json.dump将其转储到文件中。将要写入的对象和类似文件的对象传递给它。在

...


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)

参考:

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

相关问题 更多 >