I am using Python 2.6 with simplejson version 3.10.0
I am new to Python so please forgive any errors in code or lack of "python-ness". I am open to constructive criticism of course.
I have a custom object I created with three attributes (min, max, and value). I am adding a list of these objects as a value to a key in a dictionary. The key is a variable name and the value is the list of custom objects. I want to do a JSON dump of this dictionary and have something that looks like this:
{
"transforms": {
"variable1":[
{min:200,max:300,value:10},
{min:300,max:500,value:20}
]
}
}
The problem is I keep getting this error when doing a json dumps call:
TypeError: {min:200,max:300,value:10} is not JSON serializable
There is probably something I am missing or doing wrong with defining my custom object, but I haven't been able to figure it out. Here is the full Python code:
def createTransform(minBin, maxBin, value):
transform = Transform(minBin, maxBin, value)
return transform
def createDict():
finalDict = {}
varTransforms = []
varTransforms.append(createTransform(200, 300, 10))
varTransforms.append(createTransform(400, 500, 20))
finalDict.update({"variable1":varTransforms})
return finalDict
class Transform:
minBin = 0
maxBin = 0
value = 0
def __init__(self, minBin, maxBin, value):
self.minBin = minBin
self.maxBin = maxBin
self.value = value
def __str__(self):
return "{" + "min:" + str(self.minBin) + "," + "max:" + str(self.maxBin) + "," + "value:" + str(self.value) + "}"
def __repr__(self):
return self.__str__()
allTransforms = createDict()
print json.dumps({'transforms': allTransforms})
Any help is appreciated it, thank you.
Also, I am able to get this to work if I change
allTransforms = createDict()
to allTransforms = str(createDict())
but it results in having extra quotations and doing a .strip('"') on the result of Json.dumps does not remove them.