JSON serializer for objects not serializable by default json code
4825
def json_datetime_serial(obj):
    """"""
    if isinstance(obj, (datetime, date)):
        serial = obj.isoformat()
        return serial

    if ObjectId is not None and isinstance(obj, ObjectId):
        # TODO: try to use bson.json_util instead
        return str(obj)

    raise TypeError("Type not serializable")
1091499
def serialize(self):
        
        try:
            return jsonpickle.encode(self, unpicklable=False)
        except Exception:
            log.exception("got an exception during serialization")
758509
def to_json(obj):
    """"""
    i = StringIO.StringIO()
    w = Writer(i, encoding='UTF-8')
    w.write_value(obj)
    return i.getvalue()
305248
def json(
        self,
        *,
        include: 'SetStr' = None,
        exclude: 'SetStr' = None,
        by_alias: bool = False,
        skip_defaults: bool = False,
        encoder: Optional[Callable[[Any], Any]] = None,
        **dumps_kwargs: Any,
    ) -> str:
        
        encoder = cast(Callable[[Any], Any], encoder or self._json_encoder)
        return json.dumps(
            self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults),
            default=encoder,
            **dumps_kwargs,
        )
1008551
def serialize(self, null_values=False):
    
    ret = {}
    property_dict = dict(self.__class__.__dict__)  # contain view definition defaults
    property_dict.update(self.__dict__)  # overrides done at runtime

    for k in property_dict.keys():
      if k[:1] == "_" or (property_dict[k] is None and not null_values):
        continue

      v = property_dict[k]

      if isinstance(v, list):
        v_items = []
        for v_item in v:
          if self._isclass(v_item.__class__, BaseView):
            v_item_val = v_item.serialize(null_values=null_values)
            if not null_values and len(v_item_val) == 0:
              continue
            v_items.append(v_item_val)
          elif self._isclass(v_item, BaseView):  # when were passed Class instead of instance
            pass
          else:
            v_items.append(v_item)

        ret[k] = v_items
      elif self._isclass(v.__class__, BaseView):
        ret[k] = v.serialize(null_values=null_values)
      elif self._isclass(v, BaseView):  # when were passed Class instead of instance
        pass
      else:
        ret[k] = v

    return ret
935
def json_encode_default(obj):
    '''
    
    '''
    if isinstance(obj, (datetime, date)):
        result = dt2ts(obj)
    else:
        result = json_encoder.default(obj)
    return to_encoding(result)
285058
function serialize(model) {
    var data = model.toJSON();
    Object.keys(data).forEach(function serializeRecur(key) {
        var value = data[key];
        // if any value can be serialized toJSON() then do it
        if (value && value.toJSON) {
            data[key] = data[key].toJSON();
        }
    });
    return data;
}
390920
def serialize(self, obj):
        """"""
        if hasattr(obj, '_jsid'):
            return {'immutable': False, 'value': obj._jsid}
        else:
            obj_json = {'immutable': True}
            try:
                json.dumps(obj)
                obj_json['value'] = obj
            except:
                pass
            if callable(obj):
                guid = str(uuid.uuid4())
                callback_registry[guid] = obj
                obj_json['callback'] = guid
            return obj_json
1061785
def _unjsonify(x, isattributes=False):
    """"""
    if isattributes:
        obj = json.loads(x)
        return dict_class(obj)
    return json.loads(x)
1324488
def serialize(obj):
    """"""
    if isinstance(obj, datetime.datetime):
        serial = obj.isoformat(sep='T')
        return serial

    if isinstance(obj, uuid.UUID):
        serial = str(obj)
        return serial

    try:
        return obj.__dict__
    except AttributeError:
        return str(obj)
    except Exception as e:
        strval = 'unknown obj'
        exceptval = 'unknown err'
        try:
            strval = str(obj)
            exceptval = repr(e)
        except Exception:
            pass
        return 'json fail {} {}'.format(exceptval, strval)
929447
def jsonify(obj):  # pylint: disable=too-many-return-statements
    
    # Call the `to_json` method if available and add metadata.
    if hasattr(obj, 'to_json'):
        d = obj.to_json()
        _push_metadata(d, obj)
        return jsonify(d)

    # If we have a numpy array, convert it to a list.
    if isinstance(obj, np.ndarray):
        return obj.tolist()

    # If we have NumPy datatypes, convert them to native types.
    if isinstance(obj, (np.int32, np.int64)):
        return int(obj)
    if isinstance(obj, np.float64):
        return float(obj)

    # Recurse over dictionaries.
    if isinstance(obj, dict):
        return _jsonify_dict(obj)

    # Recurse over object dictionaries.
    if hasattr(obj, '__dict__'):
        return _jsonify_dict(obj.__dict__)

    # Recurse over lists and tuples.
    if isinstance(obj, (list, tuple)):
        return [jsonify(item) for item in obj]

    # Otherwise, give up and hope it's serializable.
    return obj
388169
def _encode_json(obj):
    '''
    
    '''
    def _dump_obj(obj):
        if isinstance(obj, dict):
            return obj
        d = dict()
        for k in dir(obj):
            if not k.startswith('_'):
                d[k] = getattr(obj, k)
        return d
    return json.dumps(obj, default=_dump_obj)
154087
def json_data(self, instance, default=None):
        
        value = self.get(instance)
        return value or default
429515
def make_serializable(data):
    """"""
    if is_serializable(data):
        return data

    # if numpy array convert to list
    try:
        return data.tolist()
    except AttributeError:
        pass
    except Exception as e:
        logger.debug('{} exception ({}): {}'.format(type(e).__name__, e, data))

    # try serializing each child element
    if isinstance(data, dict):
        return {key: make_serializable(value) for key, value in data.items()}
    try:
        return [make_serializable(element) for element in data]
    except TypeError:  # not iterable
        pass
    except Exception:
        logger.debug('Could not serialize {}; converting to string'.format(data))

    # last resort: convert to string
    return str(data)
851875
def json_encode(obj: Instance, **kwargs) -> str:
    
    return json.dumps(obj, cls=JsonClassEncoder, **kwargs)
1071138
def to_representation(self, obj):
        
        many = isinstance(obj, collections.Iterable) \
            or isinstance(obj, models.Manager) \
            and not isinstance(obj, dict)

        assert self.serializer is not None \
            and issubclass(self.serializer, serializers.ModelSerializer), (
                "Bad serializer defined %s" % self.serializer
            )

        extra_params = {}
        if issubclass(self.serializer, ModelPermissionsSerializer):
            extra_params['cached_allowed_fields'] =\
                self.parent.cached_allowed_fields

        ser = self.serializer(obj, context=self.context, many=many,
                              **extra_params)
        return ser.data
643954
def serialize(self, data):
        
        if data is None:
            return None
        elif isinstance(data, dict):
            return serializer.Serializer().serialize(data)
        else:
            raise Exception(_("Unable to serialize object of type = '%s'") %
                            type(data))