Forum Discussion

MBB's avatar
MBB
Occasional Contributor
4 years ago

json deserialization

I have a dictionary of named objects that I've serialized.  When I deserialize it in TC, it seems to understand that it's a dictionary and it shows the names as its keys, but the objects don't show up as objects.  It looks to me like each one is itself a dictionary.  This is not how the same code works for me in PyCharm.

 

With your permission, I'll show the serialized object and then the code:

{
    "company1": {
        "py/object": "__main__.Company",
        "number": "1"
    },
    "company2": {
        "py/object": "__main__.Company",
        "number": "2"
    },
    "company3": {
        "py/object": "__main__.Company",
        "number": "3"
    }
}
class Company:
    def __init__(self, number):
        self.number = number

 

r = open("c:\\temp\\test.json", 'r')
todecode = r.read()
decoded = jsonpickle.decode(todecode)
print(decoded["company1"].number)
print(decoded["company2"].number)
print(decoded["company3"].number)

 

That code works in PyCharm and outputs 

1
2
3

 

The same thing in TC gives me

AttributeError: 'dict' object has no attribute 'number' 17:54:40 Normal 0.00

 

It seems to be deserializing the dictionary into tuples where the key is correct but the value is a dict, rather than a Company object.

  • I wonder if its due to parameter mismatch.

    I think the issue resides in this code block: 

    class Company:
        def __init__(self, number):
            self.number = number


    Does this code work in another IDE, not PyCharm? 

  • Just a guess here, since I don't know python

     

    You defined 

    class Company:
        def __init__(self, number):
            self.number = number

    Do you need to print self .number instead of number? 

    • MBB's avatar
      MBB
      Occasional Contributor

      Thanks for answering.

       

      I don't think that's the problem, especially given that the code works as-is when I run it in PyCharm.  In TC, when I look at the dictionary in the Watch window I see not "Company1" and a Company object, but rather "Company1" and what appears to be a dict.

      • mattb's avatar
        mattb
        Staff

        I wonder if its due to parameter mismatch.

        I think the issue resides in this code block: 

        class Company:
            def __init__(self, number):
                self.number = number


        Does this code work in another IDE, not PyCharm?