I got a class with arrays of classes as properties
class classToJson():
def __init__(self, name, image, objects1, objects2):
self.name = name
self.image = image
self.boolean = True
self.objects1 = objects1
self.objects2 = objects2
def __repr__(self):
return json.dumps(self.__dict__)
object1 and object2 class looks like this:
class object1():
value1 = 1
value2 = 0
class objects2:
def __init__(self, name, value):
self.name = name
self.value = value
This is how I create my json of the class.
obj2 = [...]
parsedObject = classToJson(name, image, [object1], obj2)
file = open("{}.json".format(name),"w")
file.write("[{}]".format(parsedObject.__repr__()))
file.close()
This works if I only use name, image
and boolean
in the class but when I include objects1
or objects2
I get the TypeError: Object of type 'type' is not JSON serializable
. Why?
The json schema I want to accomplish:
[
{
"name": "name",
"image": "image",
"boolean": true,
"objects1": [
{
"value1": 1,
"value2": 0
}
],
"objetcs2": [
{
"name": "name",
"value": "value"
}
]
}
]
Just use the built in json.dump
like so
import json
with open('file.json') as f:
json.dump([{
'name': name,
'image': image,
'boolean": True,
'object1': object1,
'object2': object2
}], f)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.