Convert an object to JSON, via the defaults set with register_json_default.

  :obj: the object to convert
192537
def json_default(obj):
  
  for default in _JSON_DEFAULTS:
    if default[0](obj):
      return default[1](obj)
  raise TypeError(repr(obj) + " is not JSON serializable")
426779
def to_json(cls, obj):
        
        return "{0}d {1}s {2}us".format(
                obj.days, obj.seconds, obj.microseconds)
9772
def _json_convert(obj, json_options=DEFAULT_JSON_OPTIONS):
    
    if hasattr(obj, 'iteritems') or hasattr(obj, 'items'):  # PY3 support
        return SON(((k, _json_convert(v, json_options))
                    for k, v in iteritems(obj)))
    elif hasattr(obj, '__iter__') and not isinstance(obj, (text_type, bytes)):
        return list((_json_convert(v, json_options) for v in obj))
    try:
        return default(obj, json_options)
    except TypeError:
        return obj
425460
def _default_json_default(obj):
    
    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        return obj.isoformat()
    else:
        return str(obj)
185568
def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
    
    if isinstance(obj, Enum):
        # Properly serialize Enums (such as OpenSslVersionEnum)
        result = obj.name

    elif isinstance(obj, ObjectIdentifier):
        # Use dotted string representation for OIDs
        result = obj.dotted_string

    elif isinstance(obj, x509._Certificate):
        # Properly serialize certificates
        certificate = obj
        result = {  # type: ignore
            # Add general info
            'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
            'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),

            # Add some of the fields of the cert
            'subject': CertificateUtils.get_name_as_text(certificate.subject),
            'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
            'serialNumber': str(certificate.serial_number),
            'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
            'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
            'signatureAlgorithm': certificate.signature_hash_algorithm.name,
            'publicKey': {
                'algorithm': CertificateUtils.get_public_key_type(certificate)
            },
        }

        dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
        if dns_alt_names:
            result['subjectAlternativeName'] = {'DNS': dns_alt_names}  # type: ignore

        # Add some info about the public key
        public_key = certificate.public_key()
        if isinstance(public_key, EllipticCurvePublicKey):
            result['publicKey']['size'] = str(public_key.curve.key_size)  # type: ignore
            result['publicKey']['curve'] = public_key.curve.name  # type: ignore
        else:
            result['publicKey']['size'] = str(public_key.key_size)
            result['publicKey']['exponent'] = str(public_key.public_numbers().e)

    elif isinstance(obj, object):
        # Some objects (like str) don't have a __dict__
        if hasattr(obj, '__dict__'):
            result = {}
            for key, value in obj.__dict__.items():
                # Remove private attributes
                if key.startswith('_'):
                    continue

                result[key] = _object_to_json_dict(value)
        else:
            # Simple object like a bool
            result = obj

    else:
        raise TypeError('Unknown type: {}'.format(repr(obj)))

    return result
1095082
def json_encoder_default(obj):
    
    if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
        if obj.size == 1:
            if np.issubdtype(obj.dtype, np.integer):
                return int(obj)
            elif np.issubdtype(obj.dtype, np.floating):
                return float(obj)

    if isinstance(obj, set):
        return list(obj)
    elif hasattr(obj, 'to_native'):
        # DatastoreList, DatastoreDict
        return obj.to_native()
    elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):
        # for np.array
        return obj.tolist()

    return obj
35591
def default(self, obj):
        
        if isinstance(obj, np.ndarray):
            data_b64 = base64.b64encode(obj.data).decode('utf-8')
            return dict(__ndarray__=data_b64,
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        elif sps.issparse(obj):
            data_b64 = base64.b64encode(obj.data).decode('utf-8')
            return dict(__ndarray__=data_b64,
                        dtype=str(obj.dtype),
                        shape=obj.shape,
                        indices=obj.indices,
                        indptr=obj.indptr)
        elif hasattr(obj, '__dict__'):
            return obj.__dict__
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)
10436
def to_dict(obj):
    
    d = _to_json_type(obj)
    if isinstance(d, dict):
        return scrub_dict(d)
    else:
        raise ValueError("The value provided must be an object.")
985676
def default(self, obj):  # pylint: disable=method-hidden
        """"""

        if hasattr(obj, 'strftime'):
            return obj.strftime("%Y-%m-%dT%H:%M:%SZ")
        elif hasattr(obj, 'get_public_dict'):
            return obj.get_public_dict()
        else:
            return json.JSONEncoder.default(self, obj)
860508
def default(self, obj):
        
        if isinstance(obj, datetime):
            return obj.isoformat()

        if issubclass(obj.__class__, Enum.__class__):
            return obj.value

        to_json = getattr(obj, 'to_json', None)
        if to_json:
            out = obj.to_json()
            if issubclass(obj.__class__, Model):
                out.update({'__type': obj.__class__.__name__})

            return out

        return JSONEncoder.default(self, obj)
1149812
def obj_to_dict(cls, obj):
        
        data = {}
        for field_name in cls.get_fields():
            try:
                value = getattr(obj, field_name)
            except AttributeError:
                # If the field doesn't exist on the object, fail gracefully
                # and don't include the field in the data dict at all. Fail
                # loudly if the field exists but produces a different error
                # (edge case: accessing an *existing* field could technically
                # produce an unrelated AttributeError).
                continue

            if callable(value):
                value = value()
            data[field_name] = value

        return data
245503
def object_to_json(obj):
    """"""
    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        return obj.isoformat()
    return str(obj)
1214069
def json_dumps(obj):
    
    try:
        return json.dumps(obj, indent=2, sort_keys=True, allow_nan=False)
    except ValueError:
        pass
    # we don't want to call do_map on the original object since it can
    # contain objects that need to be converted for JSON. after reading
    # in the created JSON we get a limited set of possible types we
    # can encounter
    json_str = json.dumps(obj, indent=2, sort_keys=True, allow_nan=True)
    json_obj = json.loads(json_str)

    def do_map(obj):
        if obj is None:
            return None
        if isinstance(obj, basestring):
            return obj
        if isinstance(obj, dict):
            res = {}
            for (key, value) in obj.items():
                res[key] = do_map(value)
            return res
        if isinstance(obj, collections.Iterable):
            res = []
            for el in obj:
                res.append(do_map(el))
            return res
        # diverging numbers need to be passed as strings otherwise it
        # will throw a parsing error on the ECMAscript consumer side
        if math.isnan(obj):
            return "NaN"
        if math.isinf(obj):
            return "Infinity" if obj > 0 else "-Infinity"
        return obj

    return json.dumps(
        do_map(json_obj), indent=2, sort_keys=True, allow_nan=False)
42556
def to_json(self, model):
        
        # Get the basic Json object from the super class
        obj = super(DefaultModelRegistry, self).to_json(model)
        # Add model parameter
        obj['parameters'] = [
            para.to_json() for para in model.parameters
        ]
        obj['outputs'] = model.outputs.to_json()
        return obj
703667
def set_json(self, obj, status=HttpStatusCodes.HTTP_200):
        
        obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x))
        self.set_status(status)
        self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json')
        self.set_content(obj)
1241952
def to_json(obj, indent=4, sort_keys=True, **kwargs):
    
    obj_dict = to_dict(obj, **kwargs)
    return json.dumps(obj_dict, indent=indent, sort_keys=sort_keys)
97710
def get(obj: JsonObj, item: str, default: JsonObjTypes=None) -> JsonObjTypes:
    
    return obj._get(item, default)