Вот небольшой класс, который я написал несколько лет назад, чтобы очистить этот недопустимый JSON, который генерирует некоторая библиотека .NET:
class DotNETDecoder(simplejson.JSONDecoder):
'''
This is a decoder to convert .NET encoded JSON into python objects
The motivation for this is the way .NET encodes dates.
See:
https://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2
.NET encodes datetimes like this: "\/Date(628318530718)\/"
'''
def __init__(self, timezone, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.parse_string = self._date_parse_string(timezone)
self.scan_once = py_make_scanner(self)
@staticmethod
def _date_parse_string(timezone):
def _parse_string(string, idx, encoding, strict):
obj = scanstring(string, idx, encoding, strict)
if isinstance(obj[0], str):
match = date_match.search(obj[0])
if match:
return [dt.datetime.fromtimestamp(
int(match.group(1)) / 1000, timezone),
obj[1]]
return obj
return _parse_string
И контрольный пример / пример:
def test_can_decode_dotnet_json_dates():
jsonstr = '{"date": "Date(1330848000000)", "f": "b", "l": [], "i": 5}'
timezone = pytz.timezone('America/New_York')
obj = json.loads(jsonstr, cls=DotNETDecoder, timezone=timezone)
assert obj['date'] == timezone.localize(dt.datetime(2012, 3, 4, 3, 0))
assert obj['f'] == "b"
assert obj['i'] == 5
assert obj['l'] == []