Uploaded image for project: 'Python Driver'
  1. Python Driver
  2. PYTHON-4885

Legacy extended json encoding of DatetimeMS is incorrect

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 4.11
    • Affects Version/s: None
    • Component/s: None
    • None
    • Python Drivers
    • Not Needed

      The legacy extended json encoding of DatetimeMS is incorrect:

      >>> dumps({'d': DatetimeMS(1)}, json_options=LEGACY_JSON_OPTIONS)
      '{"d": {"$date": "1"}}'
      

      It should be encoded as a number, not a string:

      >>> dumps({'d': DatetimeMS(1).as_datetime()}, json_options=LEGACY_JSON_OPTIONS)
      '{"d": {"$date": 1}}'
      

      Attempting to decode the incorrect string version results in a decoding error:

      >>> loads('{"d": {"$date": "1"}}')
      Traceback (most recent call last):
        File "<python-input-8>", line 1, in <module>
          loads('{"d": {"$date": "1"}}')
          ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/Users/shane/git/mongo-python-driver/bson/json_util.py", line 507, in loads
          return json.loads(s, *args, **kwargs)
                 ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
        File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/json/__init__.py", line 359, in loads
          return cls(**kw).decode(s)
                 ~~~~~~~~~~~~~~~~^^^
        File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/json/decoder.py", line 344, in decode
          obj, end = self.raw_decode(s, idx=_w(s, 0).end())
                     ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
        File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/json/decoder.py", line 360, in raw_decode
          obj, end = self.scan_once(s, idx)
                     ~~~~~~~~~~~~~~^^^^^^^^
        File "/Users/shane/git/mongo-python-driver/bson/json_util.py", line 504, in <lambda>
          kwargs["object_hook"] = lambda obj: object_hook(obj, json_options)
                                              ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
        File "/Users/shane/git/mongo-python-driver/bson/json_util.py", line 537, in object_hook
          return _PARSERS[match](dct, json_options)
                 ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
        File "/Users/shane/git/mongo-python-driver/bson/json_util.py", line 624, in _parse_canonical_datetime
          elif dtm[-6] in ("+", "-") and dtm[-3] == ":":
               ~~~^^^^
      IndexError: string index out of range
      

      This was introduced when we added DatetimeMS in PYTHON-1824.

            Assignee:
            shane.harvey@mongodb.com Shane Harvey
            Reporter:
            shane.harvey@mongodb.com Shane Harvey
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: