in my back-end code, I called R function from python with rpy2
, and I have dictionary output from my R function, and I need to render it as JSON
at my server endpoint. But output of json.dumps()
for my dictionary is really not JSON
object. I figured out because output of R function as StrVector
, I have to stringify output data in dictionary then use json.dumps
, but still couldn't get proper formatted JSON.
why json.dumps
behaved stranged on data in the dictionary? what's the right way to get proper JSON structured data at the endpoint? any thought?
input data in dictionary:
here is the data in the dictionary that returned by R function. type of this dictionary is <class 'rpy2.robjects.vectors.StrVector'>
mydict = {"score":[72.188,62.0955,19.3374],"category":"medium",
"guidance":"text description","readiness":true,
"features_used":{"name":"gcstotal","value":null,
"range_value":[3.6667,5,6.3333,7.6667,9,10.3333,11.6667,13,14.3333],
"range_frequency":[0.0024,0,0.0049,0.0016,0.0073,0.0195,0.0098,0.0138,0.9406],"importance":0}}
update:
I just did quality check for mydict
, it is <class 'rpy2.robjects.vectors.StrVector'>
, so I tried below in my code:
json.dumps(str(mydict))
then I ended up below output. I called R function from python, and I used rpy2
to do so, but the output of json.dumps()
for StrVector is not really json. why? any idea?
when I feed this dictionary to json.dumps(mydict )
, I have this output:
"{\"score\":[72.188,62.0955,19.3374],\"category\":\"medium\",
\"guidance\":\"text description\",\"readiness_flag\":true,
\"features_used\":{\"name\":\"gcstotal\",\"value\":null,
\"range_value\":[3.6667,5,6.3333,7.6667,9,10.3333,11.6667,13,14.3333],
\"range_frequency\":[0.0024,0,0.0049,0.0016,0.0073,0.0195,0.0098,0.0138,0.9406],\"importance\":0}} \n"
I just don't understand why end up with non-JSON object from json.dumps
. is it a problem from json.dumps
or I used wrong way for jsonify dictionary at server endpoint? why I have above output? any idea? thanks
update 2::
after I tried @Victor S solution, it worked for pasted dictionary, but I am not sure I can decorate mydict object as follow as follow:
def post(self):
if not request.get_json():
return bad_request('No input data provided')
raw_dict = request.json
input_json = json.dumps(raw_dict)
mydict = my_R_func(input_json)
mydict = """mydict""" ## inspired from @Victor S
res = json.loads(str(mydict))
res = json.dumps(res)
return jsonify(res)
can I decorate mydict = my_R_func(input_json); mydict = """ mydict """ ? is there any way to do this?