【问题标题】:reading JSON stored in txt file with Python使用 Python 读取存储在 txt 文件中的 JSON
【发布时间】: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。你应该 dumped str(ConfigStr) 代替。另外,请注意ConfigStr 是一个字典,而不是字符串,因此名称具有误导性。
  • 你为什么要尝试just.dump() ConfigStr 的 Python 表示,只需将 dict 传递给 json.dump()
  • json.dump(config, open(configPath, 'w'))

标签: python json python-3.x


【解决方案1】:

您应该使用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

【讨论】:

  • 感谢您的快速回复让我很开心,我对 python 很陌生,学习曲线有点长
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 2018-11-04
  • 1970-01-01
  • 2021-11-11
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多