Python 如何将嵌套字典写入JSON文件?

Python 如何将嵌套字典写入JSON文件?,python,json,dictionary,nested,Python,Json,Dictionary,Nested,如何将此词典写入JSON文件 当我将此文件转储到JSON文件时,会出现此错误 ohlc={58072071: {datetime.datetime(2021, 3, 26, 23, 20): {'high': 179.0, 'low': 179.0, 'open': 179.0, 'close': 179.0, 'volume': 2354}}} 正如我在评论中所说,问题不是因为存在嵌套字典,而是因为它们包含的数

如何将此词典写入JSON文件

当我将此文件转储到JSON文件时,会出现此错误

ohlc={58072071: {datetime.datetime(2021, 3, 26, 23, 20):
                    {'high': 179.0, 'low': 179.0, 'open': 179.0, 'close': 179.0,
                     'volume': 2354}}}

正如我在评论中所说,问题不是因为存在嵌套字典,而是因为它们包含的数据没有映射到
JSON
模块文档中显示的JSON对象

下面是一种使用函数自动转换为字符串的方法

    TypeError(f'keys must be str, int, float, bool or None, '
TypeError: keys must be str, int, float, bool or None, not datetime
输出:

from datetime import datetime
import json


DATE_FMT = '%Y-%m-%d %H:%M'

def decode_dict(d):
    result = {}
    for key, value in d.items():
        if isinstance(key, datetime):
            key = datetime.strftime(key, DATE_FMT)
        if isinstance(value, datetime):
            value = datetime.strftime(value, DATE_FMT)
        elif isinstance(value, dict):
            value = decode_dict(value)  # Recursive call.
        result.update({key: value})
    return result


if __name__ == '__main__':

    ohlc = {58072071: {datetime(2021, 3, 26, 23, 20):
                        {'high': 179.0, 'low': 179.0, 'open': 179.0, 'close': 179.0,
                         'volume': 2354}}}

    print(json.dumps(decode_dict(ohlc)))

这个错误很明显,因为在
json
数据中有
datetime
对象,并且
datetime
对象不可
json序列化
。这可能有助于回答您的问题吗?这个答案指定了如何用JSON序列化任何东西,特别是datetime:您可以在问题中添加触发此错误的代码吗?
{"58072071": {"2021-03-26 23:20":
                {"high": 179.0, "low": 179.0, "open": 179.0, "close": 179.0,
                 "volume": 2354}}}
}