I am trying to make a request for session info, and I could print out session info on python console, but can't return session info on server endpoint. The error said the object is not JSON serializable. Here is the error message:
TypeError: Object of type ListVector is not JSON serializable
I found this post relevant to my post, I tried its solution, but it didn't work for me. how can I convert rpy2.ListVector
to the dictionary that can be JSON
serializable? any solution?
my attempt:
from flask import Flask, jsonify, request
from flask_restplus import Api, Resource
import json
##
import os
os.environ['PYTHONHOME'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37"
os.environ['PYTHONPATH'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37\Lib\site-packages"
os.environ['R_HOME'] = r"C:\Program Files\R\R-3.3.2"
os.environ['R_USER'] = r"C:\Users\me\AppData\Local\Programs\Python\Python37\Lib\site-packages\rpy2"
##
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
## load R function
import rpy2
import rpy2.robjects as robjects
@api.route('/')
class AResource(Resource):
def post(self):
sess = robjects.r("sessionInfo()")
return jsonify({'sessioninfo': sess})
if __name__ == '__main__':
api.add_namespace(ns)
app.run(debug=True)
here I just simply make a request to the server endpoint, I can print out session info on console but not able to return it on server endpoint. how can I make this work? any quick thought? thanks
Is there any possible solution to fix this error? any idea?
follow up your above attempt, I fixed your problem as follow:
class AResource(Resource):
def post(self):
sess = robjects.r("sessionInfo()")
new_sess= { key : sess.rx2(key)[0] for key in sess.names }
return jsonify({'sessioninfo': str(new_sess)})
now you can see json output on your server endpoint.