@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
有关,但与它无关。 最佳答案
抱歉,我知道了。由于某种原因,在第一次运行时,它将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}
关于python - 为什么在此代码中出现“TypeError:unorderable types:str()<int()”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51093268/