Reputation: 9692
I have a model class defined as;
class SiteConfig(object):
def __init__(self,command,category,frequency,delay):
self.command=command
self.category=category
self.frequency=frequency
self.delay=delay
im calling this model from another class like;
from flask import Flask,request,jsonify
import httplib
from models.SiteConfig import *
app = Flask(__name__)
@app.route('/')
def index():
return "Endpoint is not configured", 500
@app.route('/SitePollingConfiguration',methods=['GET'])
def SitePollingConfiguration():
response = jsonify(statusCode=httplib.OK, config=BuildSiteConfig())
response.status_code = httplib.OK
return response
def BuildSiteConfig():
a= SiteConfig('20c','1',60,60)
print (a)
return a
if __name__ == '__main__':
app.run()
But im getting SiteConfig is not JSON serializable error.
How can i serialize the class object in python?
EDIT i try to use existing flask json encoder;
modified my siteconfig class like;
from flask import Flask, jsonify
from flask.json import JSONEncoder
class JsonSerializable(object):
def toJson(self):
return JSONEncoder.default(self.__dict__)
class SiteConfig(JsonSerializable):
def __init__(self,command,category,frequency,delay):
self.command=command
self.category=category
self.frequency=frequency
self.delay=delay
And then calling in my main class like;
def ATGSitePollingConfiguration():
response = jsonify(statusCode=httplib.OK, config=BuildATGSiteConfig())
response.status_code = httplib.OK
return response
def BuildATGSiteConfig():
a= SiteConfig('20c','1',60,60)
print (a)
return a
But still serializable issue. Sorry im new to python; can anyone provide simple code sample on how to achieve this?
Upvotes: 0
Views: 4720
Reputation: 2276
By default, flask uses flask.json.JSONEncoder
to encode objects as JSON. In order to jsonify
your user-defined classes you will need to create a subclass of JSONEncoder
that implements the serialisation of your class. How you implement the serialisation is up to you, but the easiest method is probably to convert your object into something that JSONEncoder
already knows about (like a dict
).
Try adding this code to your app. (You should use the first version of the SiteConfig
class that you posted, not your modified one).
from flask.json import JSONEncoder
# A customized JSON encoder that knows about your SiteConfig class
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, SiteConfig):
return obj.__dict__
return JSONEncoder.default(self, obj)
# Tell your flask app to use your customised JSON encoder
app.json_encoder = CustomJSONEncoder
With this you should get the response:
{
"config": {
"category": "1",
"command": "20c",
"delay": 60,
"frequency": 60
},
"statusCode": 200
}
See here for a similar example.
Upvotes: 1
Reputation: 34657
You may also consider jsonpickle:
import jsonpickle
frozen = jsonpickle.encode(a)
Upvotes: 0