python类JSONEncoder()的实例源码

manageprojects.py 文件源码 项目:atg-commerce-iaas 作者: oracle 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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))
rabb.py 文件源码 项目:_ 作者: zengchunyun 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
host_http_server.py 文件源码 项目:py 作者: stencila 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
test_types_extras.py 文件源码 项目:nmbs-realtime-feed 作者: datamindedbe 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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'")
test_types_extras.py 文件源码 项目:nmbs-realtime-feed 作者: datamindedbe 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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'")
objects.py 文件源码 项目:shakecast 作者: usgs 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
export_metrics.py 文件源码 项目:rca-evaluation 作者: sieve-microservices 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        return json.JSONEncoder.default(self, obj)
facade.py 文件源码 项目:python-libjuju 作者: juju 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def default(self, obj):
        if isinstance(obj, Type):
            return obj.serialize()
        return json.JSONEncoder.default(self, obj)
safe_json.py 文件源码 项目:cellranger 作者: 10XGenomics 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
frozendict_json_encoder.py 文件源码 项目:data_pipeline 作者: Yelp 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def default(self, obj):
        if isinstance(obj, frozendict):
            return dict(obj)
        return json.JSONEncoder.default(self, obj)
checkplotserver_handlers.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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.
svg.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def simplify(self, precision):
        return self.segments(precision)


# overwrite JSONEncoder for svg classes which have defined a .json() method
svg.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
recipe-580664.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def default(self, obj):
        if type(obj) in self.addedtypes:
            return self.addedtypes[type(obj)].encode(obj) 
        return json.JSONEncoder.default(self, obj)
recipe-578696.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def default(self, obj):
            if isinstance(obj, smallDuck):
                return { obj.__class__.__name__ : obj.__dict__ }
            return json.JSONEncoder.default(self, obj)
views.py 文件源码 项目:Location_Assistance 作者: KamalAwasthi 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:Location_Assistance 作者: KamalAwasthi 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
json_serialization.py 文件源码 项目:autolab_core 作者: BerkeleyAutomation 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号