【发布时间】:2019-01-19 09:46:15
【问题描述】:
如何将这种 Python 对象结构保存到文件中(最好是 JSON)?我怎样才能再次从文件中加载这个结构?
class Nested(object):
def __init__(self, n):
self.name = "Nested Object: " + str(n)
self.state = 3.14159265359
class Nest(object):
def __init__(self):
self.x = 1
self.y = 2
self.objects = []
tree = []
tree.append(Nest())
tree.append(Nest())
tree.append(Nest())
tree[0].objects.append(Nested(1))
tree[0].objects.append(Nested(2))
tree[1].objects.append(Nested(1))
tree[2].objects.append(Nested(7))
tree[2].objects.append(Nested(8))
tree[2].objects.append(Nested(9))
【问题讨论】:
-
Saving structured data with JSON 和 Python 文档中的 json module documentation 会告诉你你需要知道的一切。
-
最佳答案显示了如何使用 json 和 pickle stackoverflow.com/questions/36965507/… 来做到这一点,在我看来,如果你只在 python pickle 中加载和保存这些数据是更好的,因为它保留了确切的类型,而 json 可以仅适用于基元
-
@AntiMatterDynamite JSON 只能使用开箱即用的原语,但您始终可以编写自己的
JSONEncoder和JSONDecoder。 -
你在寻找一个嵌套的objective-Json吗?也许这个link 可以帮助你。
标签: json python-3.x