2

I have this class in Python 3.5:

class DataPoint(object):

    def __init__(self, time, value):
        self.time = time
        self.value = value

And when I try to create a JSon from an instance, doing:

json.dumps( intance_of_datapoint )

I get the error:

TypeError: < DataPoint object at 0x0123 > is not JSon Serializable

So I have tried to improve the class overwritting the repr method, like this:

class DataPoint(object):

    def __init__(self, time, value):
        self.time = time
        self.value = value

    def __str__(self):
        return json.dumps(self.__dict__)

    __repr__ = __str__

By doing that I get:

TypeError: {"value":52.29, "time":1} is not JSon serializable.

Can you guys helps me undestand why? I'm pretty lost here.

cgajardo
  • 364
  • 1
  • 2
  • 17

1 Answers1

4

You will need to convert your instance in python dict and then you can dump that dict in json.dumps(instance_dict). because, as json have its own data types, and python user defined class cannot serialize to json.

Akash Wankhede
  • 618
  • 6
  • 15