1. 程式人生 > >python json序列化巢狀的物件

python json序列化巢狀的物件

先上程式碼

class to_wpf_object():
    def __init__(self, word_area_list):

        if word_area_list is None:
            self.has_caption = False
            self.word_area_list = []
            return

        self.has_caption = True
        self.word_area_list = word_area_list

    def obj_2_dict(self):
        return {
            'has_caption': self.has_caption,
            'word_area_list': [word.obj_2_dict() for word in self.word_area_list]
        }

    def obj_2_json_string(self):
        dict = self.obj_2_dict()

        json_string = json.dumps(dict, ensure_ascii=False)
        # json_string =json.dumps(self, default=obj_2_json, ensure_ascii=False)
        return json_string


class word_area():
    def __init__(self, unicom_area):
        self.left_border = unicom_area.left_border
        self.right_border = unicom_area.right_border
        self.upper_border = unicom_area.upper_border
        self.bottom_border = unicom_area.bottom_border

        #self.alphabet_count = 1
        # 影象展示的內容
        self.content = unicom_area.content

    def add_unicom_area(self, unicom_area):
        self.left_border = min(self.left_border, unicom_area.left_border)
        self.right_border = max(self.right_border, unicom_area.right_border)
        self.upper_border = min(self.upper_border, unicom_area.upper_border)
        self.bottom_border = max(self.bottom_border, unicom_area.bottom_border)

        #self.alphabet_count = self.alphabet_count + 1

        self.content = self.content + unicom_area.content

    def obj_2_dict(self):
        return {
            'left_border':self.left_border,
            'right_border': self.right_border,
            'upper_border': self.upper_border,
            'bottom_border': self.bottom_border,
            'content': self.content
        }

    def to_json_string(self):
        dict = {}
        dict['left_border'] = self.left_border
        dict['right_border'] = self.right_border
        dict['upper_border'] = self.upper_border
        dict['bottom_border'] = self.bottom_border
        #dict['alphabet_count'] = self.alphabet_count
        dict['content'] = self.content

        json_string = json.dumps(dict, ensure_ascii=False)
        return json_string

由於csdn的新版編輯器出bug了,就長話短說了。使用 json.dumps需要把物件整體拼成一個字典,物件中物件的value值也是一個dict或者是[{}, {}, {}...]。

千萬不要先將內部的物件序列化成字串,然後再序列化外邊的物件。再複雜的結構都可以表示為一個dict,而之前不需要做任何序列化操作。