Python可序列化的对象JSON [英] Python serializable objects json

查看:103
本文介绍了Python可序列化的对象JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class gpagelet:
    """
    Holds   1) the pagelet xpath, which is a string
            2) the list of pagelet shingles, list
    """
    def __init__(self, parent):
        if not isinstance( parent, gwebpage):
            raise Exception("Parent must be an instance of gwebpage")
        self.parent = parent    # This must be a gwebpage instance
        self.xpath = None       # String
        self.visibleShingles = [] # list of tuples
        self.invisibleShingles = [] # list of tuples
        self.urls = [] # list of string

class gwebpage:
    """
    Holds all the datastructure after the results have been parsed
    holds:  1) lists of gpagelets
            2) loc, string, location of the file that represents it
    """
    def __init__(self, url):
        self.url = url              # Str
        self.netloc = False         # Str
        self.gpagelets = []         # gpagelets instance
        self.page_key = ""          # str

有没有办法让我的班级json可序列化?我担心的是递归引用.

Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference.

推荐答案

编写自己的编码器和解码器,就像return __dict__

Write your own encoder and decoder, which can be very simple like return __dict__

例如这是一个用于转储完全递归树结构的编码器,您可以对其进行增强或直接用于您的目的

e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose

import json

class Tree(object):
    def __init__(self, name, childTrees=None):
        self.name = name
        if childTrees is None:
            childTrees = []
        self.childTrees = childTrees

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if not isinstance(obj, Tree):
            return super(MyEncoder, self).default(obj)

        return obj.__dict__

c1 = Tree("c1")
c2 = Tree("c2") 
t = Tree("t",[c1,c2])

print json.dumps(t, cls=MyEncoder)

它打印

{"childTrees": [{"childTrees": [], "name": "c1"}, {"childTrees": [], "name": "c2"}], "name": "t"}

您可以类似地编写一个解码器,但是您将需要以某种方式确定它是否是您的对象,因此可能会在需要时也可以放置一个类型.

you can similarly write a decoder but there you will somehow need to identify is it is your object or not, so may be you can put a type too if needed.

这篇关于Python可序列化的对象JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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