[Python] Maintaining object copy/reference link after serialization into JSON and...

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have set of fixed standardized Python objects I serialize into JSON, and then deserialize later. In some cases I have an object somewhere in the structure that I want to copy for practical access purposes (multiple user workflows). When I first create this in Python, editing the copy of the object also edits the original object - this is correct. However, when I serialize and deserialize the Python object loses the link between copy and original, and those two objects become completely unrelated, and each is edited separately.

    Is there a way for me to serialize in a way that the JSON maintains information on object copies/links?

    Here is an example test code:



    from jsonic import serialize, deserialize
    import CompositeStandard as cs

    #testing

    obj = cs.CompositeDB()

    obj.allComposite = [cs.Ply(defects = [cs.Wrinkle()])] #creates wrinkle object under ply
    obj.allDefects = [obj.allComposite[0].defects[0]] #references the same object in allDefects collection -- same object, accessible in two locations

    obj.allDefects[0].area = 678 #This edits both instances.

    print(obj)
    print("\n\n")

    json_str2 = serialize(obj, string_output = True)

    #save as file
    with open('D:\\CAD_library_sampling\\CompoST_examples\\test_sd.json', 'w') as out_file:
    out_file.write(json_str2)

    #my JSON clearly doesn't have any way to identify the two objects are linked

    #open file
    with open('D:\\CAD_library_sampling\\CompoST_examples\\test_sd.json',"r") as in_file:
    json_str= in_file.read()

    D = deserialize(json_str,string_input=True)

    D.allDefects[0].area = 99999 #this is same as above, but only edits the one instance

    print("\n\n\n")

    print(D.allDefects[0])

    print("\n\n\n")

    print(D.allComposite[0].defects[0]) #this still prints "area=678"

    Continue reading...

Compartilhe esta Página