[英]Python: unable to print the same object twice or more using jsonpickle
In a fairly complex project I came up with this issue at some point, where nested objects should be printed and the same objects have to exist there twice or more.在一个相当复杂的项目中,我在某个时候想到了这个问题,应该打印嵌套对象并且相同的对象必须存在两次或更多次。 Here I provide a simplified version of the code to reproduce the issue:
这里我提供了一个简化版本的代码来重现这个问题:
import jsonpickle
class nickname:
def __init__(self, name:str, id:int):
self.name = name
self.id = id
class test_class:
def __init__(self, name:str, age:int, nicknames:[nickname]):
self.name = name
self.age = age
self.nicknames = nicknames
nicknames = []
nicknames.append(nickname('Bomber', 1))
nicknames.append(nickname('Roccia', 2))
test_dict = {}
test_dict['key1'] = test_class('Gigi', 12, nicknames)
test_dict['key2'] = test_class('Sandro', 14, nicknames)
test_list = []
test_list.append(test_dict['key1'])
test_list.append(test_dict['key2'])
test_list.append(test_dict['key1'])
print(jsonpickle.encode(test_list, unpicklable=False))
This gives the output:这给出了 output:
[{"name": "Gigi", "age": 12, "nicknames": [{"name": "Bomber", "id": 1}, {"name": "Roccia", "id": 2}]}, {"name": "Sandro", "age": 14, "nicknames": [null, null]}, null]
Where you can see that duplicate objects are null. Adding the make_refs=False param leads to:在哪里可以看到重复的对象是 null。添加 make_refs=False 参数会导致:
[{"name": "Gigi", "age": 12, "nicknames": [{"name": "Bomber", "id": 1}, {"name": "Roccia", "id": 2}]}, {"name": "Sandro", "age": 14, "nicknames": "[<__main__.nickname object at 0x00BF50D0>, <__main__.nickname object at 0x00BF50F0>]"}, "<__main__.test_class object at 0x00BF5110>"]
Where object references are present, but still they are not encoded.其中 object 引用存在,但它们仍未编码。
Does someone have a clue on how to resolve this issue?有人知道如何解决这个问题吗? Of course I'd like duplicate objects to be reprinted instead of "null" fields.
当然,我希望重印重复的对象而不是“空”字段。
Thanks谢谢
I believe json pickle doesn't support printing out duplicate objects.我相信 json pickle 不支持打印出重复的对象。 Instead it provides a reference to it.
相反,它提供了对它的引用。 An alternative approach is to use json.dumps and have a lambda expression to recursively convert to dictionary.
另一种方法是使用 json.dumps 并使用 lambda 表达式递归转换为字典。
import json
class nickname:
def __init__(self, name:str, id:int):
self.name = name
self.id = id
class person:
def __init__(self, name:str, age:int, nicknames:[nickname]):
self.name = name
self.age = age
self.nicknames = nicknames
nicknames = [nickname('Bomber', 1), nickname('Roccia', 2)]
test_list = [person('Gigi', 12, nicknames), person('Sandro', 14, nicknames)]
results = json.dumps(test_list, default=lambda x: x.__dict__)
print(results)
This outputs:这输出:
[{"name": "Gigi", "age": 12, "nicknames": [{"name": "Bomber", "id": 1}, {"name": "Roccia", "id": 2}]}, {"name": "Sandro", "age": 14, "nicknames": [{"name": "Bomber", "id": 1}, {"name": "Roccia", "id": 2}]}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.