JSON encoder function that handles some numpy types.
969811
def json_encoder_default(obj):
    """"""
    if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
        return str(obj)
    if isinstance(obj, np.integer):
        return str(obj)
    elif isinstance(obj, np.floating):
        return float(obj)
    elif isinstance(obj, np.ndarray):
        return list(obj)
    elif isinstance(obj, (set, frozenset)):
        return list(obj)
    raise TypeError
694678
def dict_encode(in_dict):
    """"""
    if _IS_PY2:
        out_dict = {}
        for k, v in list(in_dict.items()):
            if isinstance(v, unicode):
                v = v.encode('utf8')
            elif isinstance(v, str):
                # Must be encoded in UTF-8
                v.decode('utf8')
            out_dict[k] = v
        return out_dict
    else:
        raise NotImplementedError
219076
def json_encode(obj):
    """"""
    try:
        return json_encode.encoder.encode(obj)
    except AttributeError:
        json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
        return json_encode(obj)
82061
def register_json_encoder(self, encoder_type: type, encoder: JSONEncoder):
        
        self._json_encoders[encoder_type] = encoder
        return self
257551
function encodeArray_NUM_SHORT( encoder, data, n_type ) {

	//
	// Short Numeric Array (NUM_SHORT)
	//
	// .....  ...
	// 01110 [TYPE]
	//

	encoder.counters.arr_num_short+=1;
	encoder.log(LOG.ARR, "array.numeric.short, len="+data.length+
		", type="+_NUMTYPE[n_type]+" ("+n_type+")");

	// Encode primitives one after the other
	encoder.stream8.write( pack1b( ARR_OP.NUM_SHORT | n_type ) );
	encoder.stream8.write( pack1b( data.length, false ) );
	encoder.counters.arr_hdr+=2;

	// Encode the short array
	pickStream( encoder, n_type )
		.write( packTypedArray( convertArray( data, n_type ) ) );

}
496197
def _get_object_parser(self, json):
        
        typ = self.typ
        dtype = self.dtype
        kwargs = {
            "orient": self.orient, "dtype": self.dtype,
            "convert_axes": self.convert_axes,
            "convert_dates": self.convert_dates,
            "keep_default_dates": self.keep_default_dates, "numpy": self.numpy,
            "precise_float": self.precise_float, "date_unit": self.date_unit
        }
        obj = None
        if typ == 'frame':
            obj = FrameParser(json, **kwargs).parse()

        if typ == 'series' or obj is None:
            if not isinstance(dtype, bool):
                kwargs['dtype'] = dtype
            obj = SeriesParser(json, **kwargs).parse()

        return obj
1255709
def json_conversion(obj):
    """"""
    try:
        # numpy isn't an explicit dependency of bowtie
        # so we can't assume it's available
        import numpy as np
        if isinstance(obj, (np.ndarray, np.generic)):
            return obj.tolist()
    except ImportError:
        pass

    try:
        # pandas isn't an explicit dependency of bowtie
        # so we can't assume it's available
        import pandas as pd
        if isinstance(obj, pd.Index):
            return obj.tolist()
    except ImportError:
        pass

    if isinstance(obj, (datetime, time, date)):
        return obj.isoformat()
    raise TypeError('Not sure how to serialize {} of type {}'.format(obj, type(obj)))
287852
def convert_numpy_type(cls, dtype):
        

        m = {
            'int64': cls.DATATYPE_INTEGER64,
            'float64': cls.DATATYPE_FLOAT,
            'object': cls.DATATYPE_TEXT  # Hack. Pandas makes strings into object.
        }

        t = m.get(dtype.name, None)

        if not t:
            raise TypeError(
                "Failed to convert numpy type: '{}' ".format(
                    dtype.name))

        return t
684713
def dump(*args, **kwargs):
    
    kwargs.update(dict(cls=NumpyEncoder,
                       sort_keys=True,
                       indent=4,
                       separators=(',', ': ')))
    return _json.dump(*args, **kwargs)
616054
def json_numpy_obj_hook(dct):
    
    if isinstance(dct, dict) and '__ndarray__' in dct:
        data = np.asarray(dct['__ndarray__'], dtype=dct['dtype'])
        return data.reshape(dct['shape'])
    return dct
935
def json_encode_default(obj):
    '''
    
    '''
    if isinstance(obj, (datetime, date)):
        result = dt2ts(obj)
    else:
        result = json_encoder.default(obj)
    return to_encoding(result)
542087
def data_type_to_numpy(datatype, unsigned=False):
    """"""
    basic_type = _dtypeLookup[datatype]

    if datatype in (stream.STRING, stream.OPAQUE):
        return np.dtype(basic_type)

    if unsigned:
        basic_type = basic_type.replace('i', 'u')
    return np.dtype('=' + basic_type)
129197
def jsonstreamer(func):
    """"""
    def wrapper (self, *args, **kwds):
        gen  = func (self, *args, **kwds)
        yield "["
        firstItem  = True
        for item in gen:
            if not firstItem:
                yield ","
            else:
                firstItem = False
            yield cjson.encode(item)
        yield "]"
    return wrapper
876207
def as_json(data, **kwargs):
    

    if 'sort_keys' not in kwargs:
        kwargs['sort_keys'] = False
    if 'ensure_ascii' not in kwargs:
        kwargs['ensure_ascii'] = False

    data = json.dumps(data, **kwargs)

    return data
249364
def dumps(data, **kwargs):
    """"""

    def _encoder(value):
        if isinstance(value, datetime.datetime):
            return value.isoformat()

        if hasattr(value, "_data"):
            return value._data

        raise TypeError('Could not encode %r' % value)

    return json.dumps(data, default=_encoder, **kwargs)
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
1073145
def json_encoder_with_precision(precision, JSONEncoderClass):
    
    needs_class_hack = not hasattr(json.encoder, 'FLOAT_REPR')
    try:
        if precision is not None:
            def float_repr(o):
                return format(o, '.%sf' % precision)
            if not needs_class_hack:
                # python is not 3.5
                original_float_repr = json.encoder.FLOAT_REPR
                json.encoder.FLOAT_REPR = float_repr
            else:
                # HACK to allow usage of float precision in python 3.5
                # Needed because python 3.5 removes the global FLOAT_REPR hack

                class JSONEncoderClass(JSONEncoderClass):
                    FLOAT_REPR = float.__repr__

                    # Follows code copied from cPython Lib/json/encoder.py
                    # The only change is that in floatstr _repr=float.__repr__ is replaced

                    def iterencode(self, o, _one_shot=False):
                        """Encode the given object and yield each string
                        representation as available.

                        For example::

                            for chunk in JSONEncoder().iterencode(bigobject):
                                mysocket.write(chunk)

                        """
                        if self.check_circular:
                            markers = {}
                        else:
                            markers = None
                        if self.ensure_ascii:
                            _encoder = json.encoder.encode_basestring_ascii
                        else:
                            _encoder = json.encoder.encode_basestring

                        def floatstr(o, allow_nan=self.allow_nan, _repr=float_repr, _inf=json.encoder.INFINITY, _neginf=-json.encoder.INFINITY):
                            # Check for specials.  Note that this type of test is processor
                            # and/or platform-specific, so do tests which don't depend on the
                            # internals.

                            if o != o:
                                text = 'NaN'
                            elif o == _inf:
                                text = 'Infinity'
                            elif o == _neginf:
                                text = '-Infinity'
                            else:
                                return _repr(o)

                            if not allow_nan:
                                raise ValueError(
                                    "Out of range float values are not JSON compliant: " +
                                    repr(o))

                            return text

                        if (_one_shot and json.encoder.c_make_encoder is not None and self.indent is None):
                            _iterencode = json.encoder.c_make_encoder(
                                markers, self.default, _encoder, self.indent,
                                self.key_separator, self.item_separator, self.sort_keys,
                                self.skipkeys, self.allow_nan)
                        else:
                            _iterencode = json.encoder._make_iterencode(
                                markers, self.default, _encoder, self.indent, floatstr,
                                self.key_separator, self.item_separator, self.sort_keys,
                                self.skipkeys, _one_shot)
                        return _iterencode(o, 0)
        yield JSONEncoderClass
    finally:
        if precision is not None:
            if not needs_class_hack:
                # restore FLOAT_REPR
                json.encoder.FLOAT_REPR = original_float_repr