【发布时间】:2017-06-09 16:01:37
【问题描述】:
我想将一些配置值保存到文本文件中,以便稍后在我的代码中使用它们,所以我决定将其保存到 JSON 格式的文本文件中,但是当我尝试从文件中读取值时我收到一个错误
json.decoder.JSONDecodeError:期望用双引号括起来的属性名称:第 1 行第 2 列(字符 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)
【问题讨论】:
-
这不是有效的 JSON。你应该
dumpedstr(ConfigStr)代替。另外,请注意ConfigStr是一个字典,而不是字符串,因此名称具有误导性。 -
你为什么要尝试
just.dump()ConfigStr的 Python 表示,只需将dict传递给json.dump()。 -
json.dump(config, open(configPath, 'w'))
标签: python json python-3.x