python类转json_python的对象如何转换为json输出

import statsmodels.api as sm

import json

x1 = [[4,67,662],[9,19,618],[6,49,372],[6,33,58],[1,18,153],[2,78,938],[3,15,627],[8,55,191],[2,47,812],[2,83,946],[2,4,895],[9,37,42],[0,1,595],[7,27,392],[5,22,836],[0,12,513],[2,41,601],[3,68,615],[2,23,649],[1,98,9],[9,40,32],[5,77,798],[1,10,903],[1,53,772],[7,20,716],[2,35,678],[5,52,258],[7,31,814],[2,30,577]]

y1 = [2857.0163,2547.5962,1647.6061,343.8966,668.2108,3990.0414,2559.0662,945.1439,3393.1068,4037.1068,3596.0458,297.5798,2383.6193,1663.8839,3420.5135,2088.0197,2531.2703,2670.7878,2669.8044,332.9981,266.718,3433.975,3644.3636,3249.3518,2938.0325,2821.3308,1198.4373,3363.5752,2402.6042]

x1 = sm.add_constant(x1)

model = sm.OLS(y1, x1)

rs = model.fit()

这个rs对象包含了20多个方法和属性,我们如何方便的把他转换为可以json的格式输出呢?

首先根据rs的属性方法的清单,创建一个类,我这里只用部分属性做展示

class obj_rs:

HC0_se = list

aic = float

bic = float

bse = list

def __init__(self, HC0_se,aic,bic,bse,):

self.HC0_se = HC0_se

self.aic = aic

self.bic = bic

self.bse = bse

#对象初始化

c =obj_rs(

rs.HC0_se.tolist(),

rs.aic,

rs.bic,

rs.bse.tolist()

)

#对象序列化

c= c.__dict__

print(json.dumps(c,ensure_ascii=False,indent=4))

最后如果你用flask的话,通过下面的代码输出即可。

tmp = json.dumps(c,ensure_ascii=False,indent=4)

return Response(tmp, mimetype='application/json',headers={"Access-Control-Allow-Origin":"http://127.0.0.0:5000","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"x-requested-with,content-type","Access-Control-Allow-Credentials":"true"})

结果如下图,json就可以随便你怎么使用啦。

statsmodels的rs对象的部分属性返回的json

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值