为什么我在这个代码中得到"TypeError: unorderable types: str() < int()"?


@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}

当您使用sort_keys=True并且字典混合使用int键和string键时,这是json.dump()中的一个错误。

您应该更改self.changes,以便它对字典键使用一致的类型。或者,如果您真的不需要dataIO.save_json(),则在从调用json.dump()时不要使用sort_keys=True选项。

相关内容

  • 没有找到相关文章

最新更新