简体   繁体   English

Python:无法使用 jsonpickle 打印相同的 object 两次或更多次

[英]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.

相关问题 无法使用jsonpickle将json字符串解码为python对象 - Unable to decode a json string to a python object using jsonpickle 使用python jsonpickle创建嵌套的json对象 - Create nested json object using python jsonpickle Runtime.ImportModuleError: Unable to import module &#39;testsdk&#39;: No module named &#39;jsonpickle&#39; with Python script using AWS Lambda - Runtime.ImportModuleError: Unable to import module 'testsdk': No module named 'jsonpickle' with Python script using AWS Lambda 在python中使用jsonpickle解析多个子属性 - Using jsonpickle in python to parse multiple child attributes 将 jsonpickle 用于可串行对象时如何删除 py/object - how to remove the py/object when using jsonpickle to seriable object 为两次解码的jsonpickle实现可迭代 - Implementing iterable for jsonpickle decoded twice Python jsonpickle 错误:&#39;OrderedDict&#39; 对象没有属性 &#39;_OrderedDict__root&#39; - Python jsonpickle error: 'OrderedDict' object has no attribute '_OrderedDict__root' 避免使用指向另一个 object 的 py/id 指针的 jsonpickle - Avoid jsonpickle using py/id pointer to another object 使用jsonpickle从python中的json序列化中排除字段 - excluding fields from json serialization in python using jsonpickle 使用jsonpickle进行类型演变(python) - type evolution with jsonpickle (python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM