As I said in comment the problem isn't due to there being nested dictionaries, it's because they contain data that don't map to the JSON objects shown in the table in the json
module's documentation.
Here's a way to automate their conversion to strings using the datetime.strftime()
function.
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)))
Output:
{"58072071": {"2021-03-26 23:20":
{"high": 179.0, "low": 179.0, "open": 179.0, "close": 179.0,
"volume": 2354}}}
}