python使用属性将自定义对象转换为json
在瓶子框架或python中,是否有一种方法可以使用对象的属性将自定义对象转换为json? 我看到一些帖子建议在自定义类上编写python使用属性将自定义对象转换为json,python,bottle,Python,Bottle,在瓶子框架或python中,是否有一种方法可以使用对象的属性将自定义对象转换为json? 我看到一些帖子建议在自定义类上编写到_json(self)类方法。我想知道是否有任何自动化的方法来做同样的事情 来自Java世界,希望使用XmlRootElement注释(或python术语中的decorator)实现Jackson类型的模块。但到目前为止还没有找到 更新我不想使用\uu dict\uu元素。相反,您希望使用自定义类的属性来构建json。您可以使用装饰器来“标记”需要表示的属性。 您仍然需要
到_json(self)
类方法。我想知道是否有任何自动化的方法来做同样的事情
来自Java世界,希望使用XmlRootElement
注释(或python术语中的decorator)实现Jackson
类型的模块。但到目前为止还没有找到
更新我不想使用
\uu dict\uu
元素。相反,您希望使用自定义类的属性来构建json。您可以使用装饰器来“标记”需要表示的属性。
您仍然需要编写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()
印刷品
{"surname": "world", "name": "hello"}
您可以使用装饰器来“标记”需要表示的属性。 您仍然需要编写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()
印刷品
{"surname": "world", "name": "hello"}
我想你需要看看其他的序列化库。。。json只能处理基本类型(字符串、整数、列表、dict等)。。。泡菜可以处理更多。。。如果您需要定义自定义类型之类的东西,那么您可能需要使用YAML(这有点恶心……但我认为这与您在java中询问的内容类似),我想您可能需要查看其他一些序列化库。。。json只能处理基本类型(字符串、整数、列表、dict等)。。。泡菜可以处理更多。。。如果您需要定义自定义类型之类的东西,那么您可能需要使用YAML(这有点恶心……但我认为这与您在java中提出的问题类似),是否有用于此的库?使用舒适的decorator,可以在json中指定不同的名称、默认值等,就像Java和C#中其他强大的json解析器一样。是否有用于此的库?与Java和C#中其他功能强大的json解析器一样,使用舒适的decorator在json中指定不同的名称、默认值等。