简体   繁体   English

如何从Python函数将对象作为JSON对象返回?

[英]How to return objects as JSON objects from Python function?

Here's my python module: 这是我的python模块:

#!/usr/bin/python

import rpy2.robjects as robjects
import MySQLdb as mdb
import json
import rpy2.robjects.vectors as ro
r= robjects.r

class Deviation:
    def __init__(self):
        print("Standard Deviation")

    def s_deviation(self):
        con = mdb.connect('localhost', 'root', 'devil', 'data')        
        cursor = con.cursor()
        cursor.execute("SELECT * FROM traffic")
        rows = cursor.fetchall()
        rows = list(rows)
        a = [x[1] for x in rows]
        result = ro.IntVector(a)
        a = r.sd(result)
        print a

def deviation():
    dev = Deviation()
    deviation = dev.s_deviation()

The function deviation() from this module when called returns the result as R vector. 调用此模块时的函数偏差()将结果作为R向量返回。 How do I make this return the result as Json objects? 如何使它作为Json对象返回结果? Thank you! 谢谢!

Use json.dumps or simplejson.dumps (depending on your python version). 使用json.dumpssimplejson.dumps (取决于您的python版本)。 You use it like this: 您可以这样使用它:

>> print( simplejson.dumps( { "dev": dev.s_deviation() } ) )
'{"dev":1.456}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM