1 year ago
#355558
Alphanum3ric
JSON isinstance decoder is only decoding the strings to numbers, but not dates
I have a JSON file that has dates and integers in them. All of them are showing as strings. I used a JSON decoder to get the strings parsed into integers, but I am having issues getting the date strings into actual date format. My JSON file is below:
{"Time Open": "71", "Name": "John Doe", "Date Closed": "", "Date Created": "4/11/2021", "Due Date": "5/29/2021", "TimeStamp": "08/09/2021 00:00:00 AM"}
So far I used the "isinstance" to parse the Time Open strings into integers, but the "isinstance" isn't working for changing the dates "4/11/2021" to "2021-04-11" Seems like its not detecting my datetime.datetime "isinstance". Any help will be appreciated. I have my code below.
from datetime import datetime
class Decoder(json.JSONDecoder):
def decode(self, s):
result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x
return self._decode(result)
def _decode(self, o):
if isinstance(o, str):
try:
return int(o)
except ValueError:
return o
elif isinstance(o, datetime):
try:
return datetime.datetime.strptime(o, "%m/%d/%Y").strftime("%Y-%m-%d")
except ValueError:
return o
elif isinstance(o, dict):
return {k: self._decode(v) for k, v in o.items()}
elif isinstance(o, list):
return [self._decode(v) for v in o]
else:
return o
I'm using json.loads to go to this Decoder class as below:
json_doc = json.loads(doc, cls=Decoder)
python
json
datetime
jsondecoder
encoder-decoder
0 Answers
Your Answer