python使用属性将自定义对象转换为json

2024-10-03 02:41:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在Bottle框架或python中,有没有一种方法可以使用对象的属性将自定义对象转换为json? 我看到一些文章建议在自定义类上编写to_json(self)类的方法。想知道有没有自动的方法来做同样的事?在

来自Java世界,希望使用Jackson类型的带有XmlRootElement注释的模块(或者python术语中的decorator)。但到目前为止还没有找到。在

更新我不想使用__dict__元素。相反,希望使用自定义类的属性来构建json。在


Tags: to对象方法self框架jsonbottle类型
1条回答
网友
1楼 · 发布于 2024-10-03 02:41:52

您可以使用decorator来“标记”需要表示的属性。 您仍然需要编写一个to_json函数,但只需在基类中定义一次

下面是一个简单的例子:

import json
import inspect

def viewable(fnc):
        '''
            Decorator, mark a function as viewable and gather some metadata in the process

        '''
        def call(*pargs, **kwargs):
                return fnc(*pargs, **kwargs)
        # Mark the function as viewable
        call.is_viewable = True
        return call

class BaseJsonable(object):

    def to_json(self):
        result = {}
        for name, member in inspect.getmembers(self):
            if getattr(member, 'is_viewable', False):
                value = member()
                result[name] = getattr(value, 'to_json', value.__str__)()
        return json.dumps(result)

class Person(BaseJsonable):

    @viewable
    def name(self):
        return self._name


    @viewable
    def surname(self):
        return self._surname

    def __init__(self, name, surname):
        self._name = name
        self._surname = surname


p = Person('hello', 'world')
print p.to_json()

印刷品

^{pr2}$

相关问题 更多 >