【问题标题】:Python JSON File FormattingPython JSON 文件格式
【发布时间】:2021-04-16 20:18:43
【问题描述】:

您好,我正在尝试创建 JSON 文件,但无法格式化文件。 下面我将提供代码和输出。

代码:

def writeToFile(self):
    self.json_conceivement = os.path.join("./",'NoobPremeNewEggLogIn.json')
    self.accounts = {}
    if os.path.exists(self.json_conceivement):
      try:
          with open(self.json_conceivement) as f:
              self.accounts = dict(json.loads(f.read()))
      except:
          pass
      self.accounts = {}
    else:
      try:
          with open(self.json_conceivement) as f:
              self.accounts = {}
      except:
          pass
      self.accounts['Profiles'] = []
      
  
    self.autoSave()

def autoSave(self):
   with open(self.json_conceivement, "a", encoding='utf-8') as outfile:
       json.dump(dict(self.accounts.items()), outfile,ensure_ascii=False, indent=4)

输出:(如果我运行一次,预计)

{
    "Profiles": []
}

输出:(如果我运行两次,不正确)

{
    "Profiles": []
}{}

想要的输出:

{
    "Profiles": [{}]
}

任何帮助将不胜感激

【问题讨论】:

  • 不以a追加模式打开文件应该可以。
  • 您以“追加”模式打开文件。这就是为什么您第二次运行脚本时 json 不正确的原因。更改您的“自动保存”功能。

标签: python json python-3.x list dictionary


【解决方案1】:

改变这一行

with open(self.json_conceivement, "a", encoding='utf-8') as outfile:

with open(self.json_conceivement, "w", encoding='utf-8') as outfile:

【讨论】:

  • 有了这个,我第二次运行它,它会覆盖数据,只写“{}”
  • 期待什么? Profiles是列表吗?如果是,则空列表应为“[]”,如果是对象,则应为“{}”
  • 我已经提供了上面的预期输出,我希望“{}”进入“[]”。
  • 我认为,您在第一个 IF 语句中覆盖了“self.accounts = {}”。
  • 请避免裸露的例外。至少使用 'except Exception:'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
相关资源
最近更新 更多