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

How do I write this dictionary into a JSON file?

I am getting this error when I am dumping this to JSON file

    TypeError(f'keys must be str, int, float, bool or None, '
TypeError: keys must be str, int, float, bool or None, not datetime
martineau
  • 119,623
  • 25
  • 170
  • 301
akshay07
  • 1
  • 4
  • 2
    That error is obvious cause you have `datetime` object in `json` data, and `datetime` object is not `json serializable`. – ThePyGuy Mar 26 '21 at 18:20
  • 1
    This might help https://stackoverflow.com/questions/21560433/how-to-write-a-nested-dictionary-to-json – Ashok Mar 26 '21 at 18:22
  • Does this answer your question? [How to write a nested dictionary to json](https://stackoverflow.com/questions/21560433/how-to-write-a-nested-dictionary-to-json) – iacob Mar 26 '21 at 18:24
  • 3
    This answer specifies how to JSON serialize anything, including datetime specifically: https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/36142844#36142844 – Random Davis Mar 26 '21 at 18:27
  • The problem has nothing to do with nested dictionaries. What part of the error message is unclear? – martineau Mar 26 '21 at 18:35
  • These arent solving the problem – akshay07 Mar 26 '21 at 18:36
  • I am getting the same error as mentioned above – akshay07 Mar 26 '21 at 18:38
  • 1
    Could you add the code that triggers this error in your question? – Yves Gurcan Mar 26 '21 at 18:38
  • You have to convert the `datetime` into something the `json` module understands — as shown in [this table](https://docs.python.org/3/library/json.html#json.JSONEncoder) in the documentation. In this case I'd suggest a string via [`strftime()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime). – martineau Mar 26 '21 at 18:39
  • Thanks for your advice ,it got solved m i converted the DateTime using strftime – akshay07 Mar 26 '21 at 18:48

1 Answers1

0

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}}}
}
martineau
  • 119,623
  • 25
  • 170
  • 301