简体   繁体   English

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

[英]python convert custom object to json using properties

In Bottle framework or python in general, is there a way to convert a custom object to json using the properties of the object? 在Bottle框架或python中,有没有办法使用对象的属性将自定义对象转换为json? I saw few posts which recommend to write to_json(self) kind sort of method on the custom class. 我看到很少有帖子建议在自定义类上编写to_json(self)类的方法。 Was wondering if there is any automated way of doing the same? 想知道是否有任何自动化方式做同样的事情?

Coming from Java world, was hoping for Jackson type of module with XmlRootElement annotation (or decorator in python terms). 来自Java世界,希望Jackson类型的模块具有XmlRootElement注释(或python术语中的装饰器)。 But didn't find any so far. 但到目前为止没有找到任何东西。

UPDATE I do not want to use __dict__ elements. 更新我不想使用__dict__元素。 Instead want to use properties of my custom class to build the json. 而是想使用我的自定义类的属性来构建json。

You could use a decorator to "mark" the properties that needs to be represented. 您可以使用装饰器“标记”需要表示的属性。 You would still need to write a to_json function, but you will only need to define it once in the base class 您仍然需要编写to_json函数,但您只需要在基类中定义一次

Here's a simple example: 这是一个简单的例子:

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()

Prints 打印

{"surname": "world", "name": "hello"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM