使用Python轻松进行JSON编码 [英] Easy JSON encoding with Python

查看:79
本文介绍了使用Python轻松进行JSON编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手(我使用python 3),我正在尝试使用JSon中的一个字符串和两个列表作为成员序列化一个类.我发现python标准中有一个json库,但似乎我需要手动实现序列化方法.是否有一个JSon编码器,我可以在其中简单地传递一个对象,并以字符串形式接收序列化的对象,而无需实现序列化方法. 示例:

I'm quite new to python (I use python 3), and i'm trying to serialize a class with one string and two lists as members in JSon. I found that there's a json lib in the python standart but it seems that I need to manually implement a serialization method. Is there a JSon encoder where I can simply pass an object, and receive the serialized object as string without having to implement a serialization method. Example:

class MyClass:
    pass

if __name__ == '__main__':
    my_name = "me"
    my_list = {"one","two"}
    my_obj = MyClass()
    my_obj.name = my_name;
    my_obj.my_list = my_list


    serialized_object = JSONserializer.serialize(my_obj).

谢谢.

推荐答案

不了解任何预构建的内容,但是如果您的对象足够简单,则可以编写一个.覆盖JSONEncoder中的默认方法以查看inspect.getmembers(obj)(inspect是获取__dict__中的属性集的更易读的方法).

Don't know of anything pre-built, but you can write one if your objects are simple enough. Override the default method in the JSONEncoder to look at inspect.getmembers(obj) (inspect is a more readable way of getting at sets of attributes in __dict__).

#!/usr/bin/env python3

import inspect
from json import JSONEncoder


class TreeNode:

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


class ObjectJSONEncoder(JSONEncoder):

    def default(self, reject):
        is_not_method = lambda o: not inspect.isroutine(o)
        non_methods = inspect.getmembers(reject, is_not_method)
        return {attr: value for attr, value in non_methods
                if not attr.startswith('__')}


if __name__ == '__main__':
    tree = TreeNode(42,
        TreeNode(24),
        TreeNode(242),
    )
    print(ObjectJSONEncoder().encode(tree))

更新:@Alexandre Deschamps说,isroutine比某些输入方法更好.

Update: @Alexandre Deschamps says isroutine works better than is method for some input.

这篇关于使用Python轻松进行JSON编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆