#!/usr/bin/python
# -*- coding: ascii -*-
import re
import cjson
from datetime import date, datetime
re_datetime=r'new\sDate\(Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)\)'
def json2datetime(json):
'''Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed.'''
if json[:18]!='new Date(Date.UTC(' or json[-2:]!='))':
raise ValueError('Not a JSON UTC Date: %s'%json)
args=json[18:-2].split(',')
try:
args=map(int, args)
except ValueError:
raise ValueError('Invalid arguments: %s'%json)
if len(args)==3: return date(*args)
if len(args)==6: return datetime(*args)
if len(args)==7:
args[6]*=1000
return datetime(*args)
raise ValueError('Invalid number of arguments: %s'%json)
def dateDecoder(json,idx,re=re.compile(re_datetime)):
'''Decodes JSON Date object into a date or datetime object.'''
m=re.match(json, idx)
if not m:
s=json[idx:]
if len(s)>100:
s=s[:100]+'...'
raise DecodeError('cannot parse JSON string as Date object: %s'%s)
s=m.start()
e=m.end()
dt=json2datetime(json[s:e])
return (dt,e-s) # must return (object, character_count) tuple
def decode(json):
return cjson.decode(json, extension=dateDecoder)
json='new Date(Date.UTC(1990,12,31))'
print repr(decode(json))
Traceback (most recent call last):
File "./jsonhiba.py", line 45, in ?
print repr(decode(json))
File "./jsonhiba.py", line 42, in decode
return cjson.decode(json, extension=dateDecoder)
File "./jsonhiba.py", line 38, in dateDecoder
dt=json2datetime(json[s:e])
File "./jsonhiba.py", line 18, in json2datetime
args=map(int, args)
cjson.DecodeError: cannot parse JSON description: new Date(Date.UTC(19