Deserialize JSON into python datetime objects.
354687
def load_with_datetime(pairs):
    """"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = dateutil.parser.parse(v)
            except ValueError:
                d[k] = v
        else:
            d[k] = v             
    return d
867970
def from_json(cls, json):
        """"""
        obj = cls(name=json['name'],
                  code=json['code'],
                  numeric_code=json['numeric_code'],
                  symbol=json['symbol'],
                  exponent=json['exponent'],
                  entities=json['entities'],
                  withdrawal_date=json['withdrawal_date'],
                  subunits=json['subunits'])
        return obj
660509
def _deserialize(self, value, attr, data, **kwargs):
        """"""
        if not value:  # falsy values are invalid
            self.fail('invalid')
        try:
            return utils.from_iso_time(value)
        except (AttributeError, TypeError, ValueError):
            self.fail('invalid')
54539
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'key_as_string') and self.key_as_string is not None:
            _dict['key_as_string'] = datetime_to_string(self.key_as_string)
        if hasattr(self, 'key') and self.key is not None:
            _dict['key'] = self.key
        if hasattr(self,
                   'matching_results') and self.matching_results is not None:
            _dict['matching_results'] = self.matching_results
        if hasattr(self, 'event_rate') and self.event_rate is not None:
            _dict['event_rate'] = self.event_rate
        return _dict
543377
def convert_dict_to_datetime(obj_map):
    """"""
    converted_map = {}
    for key, value in obj_map.items():
        if isinstance(value, dict) and 'tzinfo' in value.keys():
            converted_map[key] = datetime.datetime(**value)
        elif isinstance(value, dict):
            converted_map[key] = convert_dict_to_datetime(value)
        elif isinstance(value, list):
            updated_list = []
            for internal_item in value:
                if isinstance(internal_item, dict):
                    updated_list.append(convert_dict_to_datetime(internal_item))
                else:
                    updated_list.append(internal_item)
            converted_map[key] = updated_list
        else:
            converted_map[key] = value
    return converted_map
657407
def json_serial(obj):
        

        if isinstance(obj, (datetime.datetime, datetime.date)):
            return obj.isoformat()

        raise TypeError('Type {} not serializable.'.format(type(obj)))
13658
def serialize(obj):
    """"""
    # Record class and module information for deserialization
    result = {'__class__': obj.__class__.__name__}
    try:
        result['__module__'] = obj.__module__
    except AttributeError:
        pass
    # Convert objects to dictionary representation based on type
    if isinstance(obj, datetime.datetime):
        result['year'] = obj.year
        result['month'] = obj.month
        result['day'] = obj.day
        result['hour'] = obj.hour
        result['minute'] = obj.minute
        result['second'] = obj.second
        result['microsecond'] = obj.microsecond
        return result
    if isinstance(obj, StreamingBody):
        result['body'] = obj.read()
        obj._raw_stream = StringIO(result['body'])
        obj._amount_read = 0
        return result
    # Raise a TypeError if the object isn't recognized
    raise TypeError("Type not serializable")
321539
def _deserialize(type, value)
      case type.to_sym
      when :DateTime
        Time.at(/\d/.match(value)[0].to_f).to_datetime
      when :Date
        Time.at(/\d/.match(value)[0].to_f).to_date
      when :String
        value.to_s
      when :Integer
        value.to_i
      when :Float
        value.to_f
      when :BOOLEAN
        if value.to_s =~ /\A(true|t|yes|y|1)\z/i
          true
        else
          false
        end
      when :Object
        # generic object (usually a Hash), return directly
        value
      when /\AArray<(?<inner_type>.+)>\z/
        inner_type = Regexp.last_match[:inner_type]
        value.map { |v| _deserialize(inner_type, v) }
      when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
        k_type = Regexp.last_match[:k_type]
        v_type = Regexp.last_match[:v_type]
        {}.tap do |hash|
          value.each do |k, v|
            hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
          end
        end
      else
      # model
        temp_model = GroupDocsComparisonCloud.const_get(type).new
        temp_model.build_from_hash(value)
      end
    end
1367010
def _time_from_json(value, field):
    """"""
    if _not_null(value, field):
        if len(value) == 8:  # HH:MM:SS
            fmt = _TIMEONLY_WO_MICROS
        elif len(value) == 15:  # HH:MM:SS.micros
            fmt = _TIMEONLY_W_MICROS
        else:
            raise ValueError("Unknown time format: {}".format(value))
        return datetime.datetime.strptime(value, fmt).time()
500322
def json_serial(obj):
    """"""
    if isinstance(obj, LegipyModel):
        return obj.to_json()
    elif isinstance(obj, (datetime.date, datetime.datetime)):
        return obj.isoformat()
    raise TypeError("Type {0} not serializable".format(repr(type(obj))))
593990
def to_dict(self, data=True):
        """"""
        item = {'dims': self.dims,
                'attrs': decode_numpy_dict_values(self.attrs)}
        if data:
            item['data'] = ensure_us_time_resolution(self.values).tolist()
        else:
            item.update({'dtype': str(self.dtype), 'shape': self.shape})
        return item
1361690
def from_json(cls, json_obj):
        
        if isinstance(json_obj, str):
            json_obj = json.loads(json_obj)

        type = None
        time = None
        data = None
        if cls.TYPE_FIELD_NAME in json_obj:
            type = json_obj[cls.TYPE_FIELD_NAME]

        if cls.TIME_FIELD_NAME in json_obj:
            time = json_obj[cls.TIME_FIELD_NAME]
        else:
            raise InvalidEventError("{field} must be present!".format(
                field=cls.TIME_FIELD_NAME))

        if cls.DATA_FIELD_NAME in json_obj:
            data = json_obj[cls.DATA_FIELD_NAME]

        return cls(type, time, data)
893830
def _parse(data):
    """"""

    if not data:
        return []
    elif isinstance(data, (tuple, list)):
        return [_parse(subdata) for subdata in data]

    # extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}}
    d = {ik: v for k in data.keys() for ik, v in data[k].items()}

    # convert datetime strings to datetime objects
    # and float number strings to float
    to_parse = dict(d)
    for k, v in to_parse.items():
        if k in {
                "name",
                "display_name",
                "display_name_with_invitation_email_address",
                "username",
                "challonge_username"}:
            continue # do not test type of fields which are always strings
        if isinstance(v, TEXT_TYPE):
            try:
                dt = iso8601.parse_date(v)
                d[k] = dt.astimezone(tz)
            except iso8601.ParseError:
                try:
                    d[k] = float(v)
                except ValueError:
                    pass

    return d
553026
def _serialize_datetime(value):
    """"""
    if not isinstance(value, (datetime, arrow.Arrow)):
        raise ValueError(u'The received object was not a datetime: '
                         u'{} {}'.format(type(value), value))
    return value.isoformat()
395794
def json2datetime(json):
        
        
        json_m = re.search(r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?', json)
        args=json_m.group(0).split(',')
        
        try:
            args=map(int, args)
        except ValueError:
            raise ValueError('Invalid arguments: %s'%json)

        if len(args)==3: 
            return datetime.datetime(args[0], args[1]+1, args[2])
        elif len(args)==6: 
            return datetime.datetime(args[0], args[1]+1, args[2], 
                                    args[3], args[4], args[5], tzinfo=UTC())
        elif len(args)==7:
            args[6]*=1000
            return datetime.datetime(args[0], args[1]+1, args[2], 
                                    args[3], args[4], args[5], args[6], tzinfo=UTC())
        raise ValueError('Invalid number of arguments: %s'%json)
237922
def deserialize(self, obj):
        """"""
        if obj['immutable']:
            return obj['value']
        else:
            guid = obj['value']
            if not guid in object_registry:
                instance = JSObject(self, guid)
                object_registry[guid] = instance
            return object_registry[guid]
5750
def _serialize(self, value, attr, obj, **kwargs):
        """"""
        if value is None:
            return None

        return int(datetime_to_timestamp(value))