如何将用户定义的 python 对象转储到 json 文件?我所说的对象是指实际对象而不是它们的属性
How to dump user defined python objects to json file? By Objects I mean actual objects and not their attributes
所以我有两个用户定义的 python 类 如下所示
class cell(object):
def __init__(self,id,x_cor,y_cor,width = cell_size,height = cell_size ,color = lightblue ):
self.id = id
self.x_cor = x_cor
self.y_cor = y_cor
self.width = width
self.height = height
self.color = color
class edge(object):
def __init__(self,pos, x_cor,y_cor,state,color = lightgreen):
global border_size
global cell_size
self.pos = pos
self.x_cor = x_cor
self.y_cor = y_cor
self.state = state
self.color = color
if self.state == "H":
self.width = cell_size+(border_size)*2
self.height = border_size
self.x_lower_bound = self.x_cor + border_size
self.x_upper_bound = self.x_cor +border_size+ cell_size
self.y_lower_bound = self.y_cor
self.y_upper_bound = self.y_cor + border_size
elif self.state == "V":
self.width = border_size
self.height = cell_size+(border_size*2)
self.x_lower_bound = self.x_cor
self.x_upper_bound = self.x_cor + border_size
self.y_lower_bound = self.y_cor + border_size
self.y_upper_bound = self.y_cor + border_size + cell_size
现在我有一个名为 cells 的二维列表
它被定义并看起来像这样 Click me.
有点乱,但你可以看到它是一个 16 x 16 的矩阵,存储了上面定义的对象 od 单元格
不,我想将这个二维数组存储在 json 文件中
这就是我正在做的
json_data = []
json_data.append(cells)
with open("default.json" , "w") as f:
json.dump(json_data,f,indent = 2)
这是我收到的终端错误
Click on the link to view
使用pickle.
它不是人类可读的,也不是 json 格式。但是此模块旨在存储 Python 个对象并在将来再次加载它。
查看更多此内容以与 json
模块进行比较。
所以我有两个用户定义的 python 类 如下所示
class cell(object):
def __init__(self,id,x_cor,y_cor,width = cell_size,height = cell_size ,color = lightblue ):
self.id = id
self.x_cor = x_cor
self.y_cor = y_cor
self.width = width
self.height = height
self.color = color
class edge(object):
def __init__(self,pos, x_cor,y_cor,state,color = lightgreen):
global border_size
global cell_size
self.pos = pos
self.x_cor = x_cor
self.y_cor = y_cor
self.state = state
self.color = color
if self.state == "H":
self.width = cell_size+(border_size)*2
self.height = border_size
self.x_lower_bound = self.x_cor + border_size
self.x_upper_bound = self.x_cor +border_size+ cell_size
self.y_lower_bound = self.y_cor
self.y_upper_bound = self.y_cor + border_size
elif self.state == "V":
self.width = border_size
self.height = cell_size+(border_size*2)
self.x_lower_bound = self.x_cor
self.x_upper_bound = self.x_cor + border_size
self.y_lower_bound = self.y_cor + border_size
self.y_upper_bound = self.y_cor + border_size + cell_size
现在我有一个名为 cells 的二维列表 它被定义并看起来像这样 Click me.
有点乱,但你可以看到它是一个 16 x 16 的矩阵,存储了上面定义的对象 od 单元格
不,我想将这个二维数组存储在 json 文件中 这就是我正在做的
json_data = []
json_data.append(cells)
with open("default.json" , "w") as f:
json.dump(json_data,f,indent = 2)
这是我收到的终端错误 Click on the link to view
使用pickle.
它不是人类可读的,也不是 json 格式。但是此模块旨在存储 Python 个对象并在将来再次加载它。
查看更多此内容以与 json
模块进行比较。