Python json 模块,JSONEncoder() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用json.JSONEncoder()

项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'")
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'")
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'")
项目:psycopg2-for-aws-lambda    作者:iwitaly    | 项目源码 | 文件源码
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'")
项目:OpenXCAccessory    作者:openxc    | 项目源码 | 文件源码
def get_status(self):
        jsonString = json.JSONEncoder().encode(
                      [ { "name":"RSU", "value": self.name},    
                      { "name": self.prefix+" Spaces_available","value": self.spaces_available},
                                          { "name": self.prefix+" Longitude","value":self.lon},
                                          { "name": self.prefix+" Latitude","value":self.lat},
                                          { "name": self.prefix+" Cost/hour","value":self.rate},
                      { "name":"Count", "value":self.count}])

        self.spaces_available = random.randrange(0,self.max_spaces,1);
        self.rate = random.randrange(0,20,1);
        self.count += 1
        data = json.dumps(jsonString)
        tdata = (data.replace("}, {","}\\\0{")).replace("\\","")
#        LOG.info("TDATA = " + tdata)
        return(tdata.replace("\"[","")).replace("]\"","")+chr(0)   # Adding a \0 to the end of the packet per the message format standards
项目:git-reviewers    作者:johnnadratowski    | 项目源码 | 文件源码
def write_json(output, end='', raw=False, file=None, flush=False):
    file = file or sys.stdout

    if len(output) == 1:
        output = output[0]

    if raw:
        json.dump(output, file, separators=(',', ':'), cls=JSONEncoder)
    else:
        json.dump(output, file, indent=4, sort_keys=True, cls=JSONEncoder)

    if flush:
        file.flush()

    if end:
        write_output(file, '', end=end, sep='', flush=flush)
项目:baka    作者:baka-framework    | 项目源码 | 文件源码
def default(self, o):
        # for Enum Type
        if isinstance(o, enum.Enum):
            return o.value

        # for Enum Select Integer
        if isinstance(o, EnumInt):
            return o.key

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

        if isinstance(o, Decimal):
            return _number_str(o)

        if isinstance(o, ObjectId):
            return str(o)

        return super(JSONEncoder, self).default(o)
项目:episode-miner    作者:estnltk    | 项目源码 | 文件源码
def to_json(self):
        """Serializes event sequences using json.

        Returns
        -------
        str
            json serialization of self. 
        """
        class EventEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Event):
                    return [obj.event_type, obj.event_time]
                if isinstance(obj, EventSequence):
                    return obj.sequence_of_events
                return json.JSONEncoder.default(self, obj)

        return json.dumps(self, ensure_ascii=False, cls=EventEncoder)
项目:plone.server    作者:plone    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, type):
            return obj.__module__ + '.' + obj.__name__
        elif isinstance(obj, InterfaceClass):
            return [x.__module__ + '.' + x.__name__ for x in obj.__iro__]  # noqa
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        if isinstance(obj, PermissionSetting):
            return obj.getName()
        if callable(obj):
            return obj.__module__ + '.' + obj.__name__
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)
项目:geo-tools    作者:Major1201    | 项目源码 | 文件源码
def to_json(o):
    import json
    from datetime import date
    from datetime import datetime

    class CJsonEncoder(json.JSONEncoder):
        def __init__(self, **kwargs):
            super(CJsonEncoder, self).__init__(**kwargs)

        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(obj, date):
                return obj.strftime("%Y-%m-%d")
            else:
                return super(CJsonEncoder, self).default(obj)
    return json.dumps(o, cls=CJsonEncoder, ensure_ascii=False)
项目:wizard    作者:honor100    | 项目源码 | 文件源码
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        if isinstance(o, datetime.date):
            return o.isoformat()
        if isinstance(o, datetime.time):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return str(o)
        return json.JSONEncoder.default(self, o)
# ????? json.dumps(yourobj, cls=DateTimeEncoder)

# class DecimalEncoder(json.JSONEncoder):
#     def _iterencode(self, o, markers=None):
#         if isinstance(o, decimal.Decimal):
#             # wanted a simple yield str(o) in the next line,
#             # but that would mean a yield on the line with super(...),
#             # which wouldn't work (see my comment below), so...
#             return (str(o) for o in [o])
#         return super(DecimalEncoder, self)._iterencode(o, markers)
项目:irida-miseq-uploader    作者:phac-nml    | 项目源码 | 文件源码
def default(self, obj):

            if isinstance(obj, Sample):
                sample_dict = dict(obj.get_dict())
                # get sample dict and make a copy of it
                sample_dict.pop("sampleProject")
                if "sequencerSampleId" in sample_dict:
                    # if the sample ID field is populated, then we've just Finished
                    # reading the run from disk and we're preparing to send data
                    # to the server. The server is using the sample ID field as the
                    # name of the sample, so overwrite whatever we *were* using to
                    # find files with the sample ID field.
                    sample_dict["sampleName"] = sample_dict["sequencerSampleId"]
                return sample_dict
            else:
                return json.JSONEncoder.default(self, obj)
项目:guillotina    作者:plone    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, type):
            return obj.__module__ + '.' + obj.__name__
        elif isinstance(obj, InterfaceClass):
            return [x.__module__ + '.' + x.__name__ for x in obj.__iro__]  # noqa
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        if isinstance(obj, PermissionSetting):
            return obj.get_name()
        if callable(obj):
            return obj.__module__ + '.' + obj.__name__
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)


# b/w compat import
项目:twitterscraper    作者:taspinar    | 项目源码 | 文件源码
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        elif isinstance(obj, collections.Iterable):
            return list(obj)
        elif isinstance(obj, datetime):
            return obj.isoformat()
        elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
            return dict(obj)
        elif hasattr(obj, '__dict__'):
            return {member: getattr(obj, member)
                    for member in dir(obj)
                    if not member.startswith('_') and
                    not hasattr(getattr(obj, member), '__call__')}

        return json.JSONEncoder.default(self, obj)
项目:inotiftpsync    作者:Major1201    | 项目源码 | 文件源码
def to_json(o):
    import json
    from datetime import date
    from datetime import datetime

    class CJsonEncoder(json.JSONEncoder):
        def __init__(self, **kwargs):
            super(CJsonEncoder, self).__init__(**kwargs)

        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(obj, date):
                return obj.strftime("%Y-%m-%d")
            else:
                return super(CJsonEncoder, self).default(obj)
    return json.dumps(o, cls=CJsonEncoder, ensure_ascii=False)
项目:incubator-airflow-old    作者:apache    | 项目源码 | 文件源码
def default(self, obj):
        # convert dates and numpy objects in a json serializable format
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif type(obj) in (np.int_, np.intc, np.intp, np.int8, np.int16,
                           np.int32, np.int64, np.uint8, np.uint16,
                           np.uint32, np.uint64):
            return int(obj)
        elif type(obj) in (np.bool_,):
            return bool(obj)
        elif type(obj) in (np.float_, np.float16, np.float32, np.float64,
                           np.complex_, np.complex64, np.complex128):
            return float(obj)

        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)
项目:qzig    作者:Seluxit    | 项目源码 | 文件源码
def default(self, obj):
        if type(obj) is value.ValuePermission:
            return obj.value
        if type(obj) is value.ValueStatus:
            return obj.value
        if type(obj) is state.StateType:
            return obj.value
        if type(obj) is state.StateStatus:
            return obj.value
        if type(obj) is value.ValueNumberType:
            return obj.__dict__
        if type(obj) is value.ValueStringType:
            return obj.__dict__
        if type(obj) is status.StatusType:
            return obj.value
        if type(obj) is status.StatusLevel:
            return obj.value
        # if type(obj) is value.ValueSetType:
        #    return obj.__dict__
        # if type(obj) is value.ValueBlobType:
        #    return obj.__dict__
        # if type(obj) is value.ValueXmlType:
        #    return obj.__dict__
        # return json.JSONEncoder.default(self, obj)
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertQuotedEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'")
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertQuotedEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'")
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:PyMiniRacer    作者:sqreen    | 项目源码 | 文件源码
def test_call_custom_encoder(self):

        # Custom encoder for dates
        class CustomEncoder(json.JSONEncoder):

            def default(self, obj):
                if isinstance(obj, datetime):
                    return obj.isoformat()

                return json.JSONEncoder.default(self, obj)

        now = datetime.now()
        js_func = """var f = function(args) {
            return args;
        }"""
        self.mr.eval(js_func)

        self.assertEqual(self.mr.call('f', now, encoder=CustomEncoder),
                         now.isoformat())
项目:nist_mni_pipelines    作者:vfonov    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, MriTransform):
            return {'name':obj.name,
                    'xfm' :obj.xfm,
                    'xfm_f':obj.xfm_f,
                    'xfm_inv' :obj.xfm_inv,
                    'xfm_f_inv':obj.xfm_f_inv,
                    'prefix':obj.prefix
                   }
        elif isinstance(obj, MriDataset):
            return {'name':obj.name,
                    'scan':obj.scan,
                    'mask':obj.mask,
                    'scan_f':obj.scan_f,
                    'mask_f':obj.mask_f,
                    'prefix':obj.prefix,
                    'add':obj.add,
                    'add_f':obj.add_f,
                    'group':obj.group,
                    'grading':obj.grading,
                   }
         # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

# kate: space-indent on; indent-width 4; indent-mode python;replace-tabs on;word-wrap-column 80;show-tabs on
项目:nist_mni_pipelines    作者:vfonov    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, MriTransform):
            return {'name':obj.name,
                    'xfm' :obj.xfm,
                    'xfm_f':obj.xfm_f,
                    'xfm_inv' :obj.xfm_inv,
                    'xfm_f_inv':obj.xfm_f_inv,
                    'prefix':obj.prefix
                   }
        elif isinstance(obj, MriDataset):
            return {'name':obj.name,
                    'scan':obj.scan,
                    'mask':obj.mask,
                    'scan_f':obj.scan_f,
                    'mask_f':obj.mask_f,
                    'prefix':obj.prefix,
                    'add':obj.add,
                    'add_f':obj.add_f
                   }
         # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)



# kate: space-indent on; indent-width 4; indent-mode python;replace-tabs on;word-wrap-column 80;show-tabs on
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def __save_msl_data(self):
        """
        Saves the keys and tokens in json file
        :return:
        """
        data = {
            "encryption_key": base64.standard_b64encode(self.encryption_key),
            'sign_key': base64.standard_b64encode(self.sign_key),
            'tokens': {
                'mastertoken': self.mastertoken
            }
        }
        serialized_data = json.JSONEncoder().encode(data)
        self.save_file(
            msl_data_path=self.kodi_helper.msl_data_path,
            filename='msl_data.json',
            content=serialized_data)
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'"))
项目:atg-commerce-iaas    作者:oracle    | 项目源码 | 文件源码
def load_project_data(project_name):
    """
    Load project data from properties file
    """    

    global identity_domain
    global username
    global image_name    
    global os_project_name
    global os_image_name      
    data_type = "project"

    identity_domain = orchestration_helper.get_config_item(project_name, project_name, 'identity_domain', data_type)
    username = orchestration_helper.get_config_item(project_name, project_name, 'username', data_type)
    image_name = orchestration_helper.get_config_item(project_name, project_name, 'image_name', data_type)
    os_project_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_project', data_type)
    os_image_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_image_name', data_type)    

    projdata = {'opc': {'Domain': identity_domain, 'username': username, 'image': image_name}, 'openstack': {'os_project_name': os_project_name, 'os_image_name': os_image_name}}
    return (json.JSONEncoder().encode(projdata))
项目:_    作者:zengchunyun    | 项目源码 | 文件源码
def format_list(json_list, columns, args, options):
    format = options.format
    formatter = None
    if format == "raw_json":
        output(json_list)
        return
    elif format == "pretty_json":
        enc = json.JSONEncoder(False, False, True, True, True, 2)
        output(enc.encode(json.loads(json_list)))
        return
    else:
        formatter = FORMATS[format]
    assert_usage(formatter != None,
                 "Format {0} not recognised".format(format))
    formatter_instance = formatter(columns, args, options)
    formatter_instance.display(json_list)
项目:py    作者:stencila    | 项目源码 | 文件源码
def default(self, object):
        try:
            iterable = iter(object)
        except TypeError:
            pass
        else:
            return list(iterable)

        try:
            properties = object.__dict__
        except AttributeError:
            pass
        else:
            return dict((key, value) for key, value in properties.items() if not key.startswith('_'))

        return JSONEncoder.default(self, object)
项目:nmbs-realtime-feed    作者:datamindedbe    | 项目源码 | 文件源码
def test_adapt_dumps(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        curs = self.conn.cursor()
        obj = Decimal('123.45')

        def dumps(obj):
            return json.dumps(obj, cls=DecimalEncoder)
        self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
            b"'123.45'")
项目:nmbs-realtime-feed    作者:datamindedbe    | 项目源码 | 文件源码
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'")
项目:shakecast    作者:usgs    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') 
                                and x != 'metadata' and x != '_sa_instance_state']:
                data = obj.__getattribute__(field)

                if isinstance(data, types.MethodType):
                    continue

                try:
                    json.dumps(data) # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:
                    try:
                        fields[field] = [str(d) for d in data]
                    except:
                        fields[field] = None
                except UnicodeEncodeError:
                    fields[field] = 'Non-encodable'
            # a json-encodable dict
            return fields

        return json.JSONEncoder.default(self, obj)
项目:rca-evaluation    作者:sieve-microservices    | 项目源码 | 文件源码
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        return json.JSONEncoder.default(self, obj)
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, Type):
            return obj.serialize()
        return json.JSONEncoder.default(self, obj)
项目:cellranger    作者:10XGenomics    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, np.ndarray) and obj.ndim == 1:
                return obj.tolist()
        elif isinstance(obj, np.generic):
            return obj.item()
        return json.JSONEncoder.default(self, obj)
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, frozendict):
            return dict(obj)
        return json.JSONEncoder.default(self, obj)
项目:astrobase    作者:waqasbhatti    | 项目源码 | 文件源码
def default(self, obj):

        if isinstance(obj, ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return obj.decode()
        else:
            return json.JSONEncoder.default(self, obj)

# this replaces the default encoder and makes it so Tornado will do the right
# thing when it converts dicts to JSON when a
# tornado.web.RequestHandler.write(dict) is called.
项目:sketch-components    作者:ibhubs    | 项目源码 | 文件源码
def simplify(self, precision):
        return self.segments(precision)


# overwrite JSONEncoder for svg classes which have defined a .json() method
项目:sketch-components    作者:ibhubs    | 项目源码 | 文件源码
def default(self, obj):
        if not isinstance(obj, tuple(svgClass.values() + [Svg])):
            return json.JSONEncoder.default(self, obj)

        if not hasattr(obj, 'json'):
            return repr(obj)

        return obj.json()


# Code executed on module load #
# SVG tag handler classes are initialized here
# (classes must be defined before)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def default(self, obj):
        if type(obj) in self.addedtypes:
            return self.addedtypes[type(obj)].encode(obj) 
        return json.JSONEncoder.default(self, obj)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def default(self, obj):
            if isinstance(obj, smallDuck):
                return { obj.__class__.__name__ : obj.__dict__ }
            return json.JSONEncoder.default(self, obj)
项目:Location_Assistance    作者:KamalAwasthi    | 项目源码 | 文件源码
def search(request):
    current_username=request.POST.get('username')
    try:
        user=User.objects.get(username=current_username)
        python_object = {'flag':'True',
                        'userName': user.username,
                        'first_name': user.first_name,
                        'last_name': user.last_name}
    except Exception as e:
        python_object = {'flag':'False'}
    datatosend=json.JSONEncoder().encode(python_object)
    return HttpResponse(datatosend)

#views for save_settings table
项目:Location_Assistance    作者:KamalAwasthi    | 项目源码 | 文件源码
def add_friends(request):
    current_username = request.POST.get('username')
    current_friendList = request.POST.get('friendList')
    try:
        username=User.objects.get(username=current_username)
    except Exception as e:
        python_object = {'status':'203'}
        datatosend=json.JSONEncoder().encode(python_object)
        return HttpResponse(datatosend)
    json_obj = json.loads(current_friendList)
    ol=[]
    try:
        existingUser = FriendList.objects.get(user__username = username)
        user_friends = existingUser.getfoo()
        for c in user_friends:
            c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
            # print type(c)
            ol.append(c)
        for c in json_obj:
            c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
            ol.append(c)
        existingUser.friendList = json.dumps(ol)
        existingUser.save()
        python_object = {'status':'200'}
    except:
        friend = FriendList(user = username)
        friend.setfoo(current_friendList) 
        friend.save()
        python_object = {'status':'200'}
    datatosend=json.JSONEncoder().encode(python_object)
    return HttpResponse(datatosend)
项目:autolab_core    作者:BerkeleyAutomation    | 项目源码 | 文件源码
def default(self, obj):
        """Converts an ndarray into a dictionary for efficient serialization.

        The dict has three keys:
        - dtype : The datatype of the array as a string.
        - shape : The shape of the array as a tuple.
        - __ndarray__ : The data of the array as a list.

        Parameters
        ----------
        obj : :obj:`numpy.ndarray`
            The ndarray to encode.

        Returns
        -------
        :obj:`dict`
            The dictionary serialization of obj.

        Raises
        ------
        TypeError
            If obj isn't an ndarray.
        """
        if isinstance(obj, np.ndarray):
            return dict(__ndarray__=obj.tolist(),
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        # Let the base class default method raise the TypeError
        return _json.JSONEncoder(self, obj)