@commands.command(pass_context=True)
@checks.serverowner()
async def change(self, ctx, change):
channel = self.bot.get_channel('432738903221469186')
change = ctx.message.clean_content[8:]
now = datetime.now()
count = len(self.changes.items()) + 1
self.changes[count] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change}
dataIO.save_json('data/local/changes.json', self.changes)
await self.bot.send_message(channel, bold("\N{SPARKLE} This change to the server was just made:") + box(change))
await self.bot.add_reaction(ctx.message, "\N{WHITE HEAVY CHECK MARK}")
这是changes.json:
{
"1" : {
"change" : "TEST",
"date" : "2018-06-29 01:07:37"
}
}
这是完整的错误:
2|cdb_laun | Traceback (most recent call last):
2|cdb_laun | File "lib/discord/ext/commands/core.py", line 50, in wrapped
2|cdb_laun | ret = yield from coro(*args, **kwargs)
2|cdb_laun | File "/root/craig/cdbot/cogs/local.py", line 73, in change
2|cdb_laun | dataIO.save_json('data/local/changes.json', self.changes)
2|cdb_laun | File "/root/craig/cdbot/cogs/utils/dataIO.py", line 20, in save_json
2|cdb_laun | self._save_json(tmp_file, data)
2|cdb_laun | File "/root/craig/cdbot/cogs/utils/dataIO.py", line 50, in _save_json
2|cdb_laun | json.dump(data, f, indent=4, sort_keys=True, separators=(",", " : "))
2|cdb_laun | File "/usr/lib64/python3.5/json/__init__.py", line 178, in dump
2|cdb_laun | for chunk in iterable:
2|cdb_laun | File "/usr/lib64/python3.5/json/encoder.py", line 429, in _iterencode
2|cdb_laun | yield from _iterencode_dict(o, _current_indent_level)
2|cdb_laun | File "/usr/lib64/python3.5/json/encoder.py", line 352, in _iterencode_dict
2|cdb_laun | items = sorted(dct.items(), key=lambda kv: kv[0])
2|cdb_laun | TypeError: unorderable types: str() < int()
我为模糊的标题和问题表示歉意,我只是经常处理JSON,在这里我不理解错误。我什至看不到要比较字符串和整数的位置。
我最初的想法是它与count = len(self.changes.items()) + 1
有关,但与否无关。
答案 0 :(得分:2)
对不起,我知道了。由于某种原因,在第一次运行时,它将JSON密钥保存为字符串。在第二轮中,将其保存为整数。 self.changes
打印为:
{'2': {'date': '2018-06-29 02:02:03', 'change': 'TEST'}, '1': {'date': '2018-06-29 01:07:37', 'change': 'TEST'}}
要解决此问题,我只是更改了
self.changes[count] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change}
到
self.changes[str(count)] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change}
答案 1 :(得分:2)
当您使用json.dump()
时,这是sort_keys=True
中的bug,并且字典包含int
和string
键的混合。
您应该更改self.changes
,以便它对字典键使用一致的类型。或者,如果您不需要的话,请从sort_keys=True
调用json.dump()
时不要使用dataIO.save_json()
选项。