如何从sqlalchemy中对象进行jsonify? [英] How to jsonify objects from sqlalchemy?

查看:105
本文介绍了如何从sqlalchemy中对象进行jsonify?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask,SQLAlchemy和javascript。我需要通过AJAX将查询结果传递给json格式的javascript,但我一直收到此错误:

I'm using Flask, SQLAlchemy and javascript. I need to pass the results of my query to javascript in the json format, through AJAX, but I keep getting this error:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <model.Cloud object at 0x7f72e40c5910> is not JSON serializable'

我的代码如下:

@app.route('/past/<user_id>')
def get_past_clouds(user_id):
    if user_id:
        clouds = model_session.query(model.User).filter_by(id=user_id).first().clouds
        if clouds != "":
            clouds_d = {}
            for idx, cloud in enumerate(clouds):
                clouds_d[idx] = cloud
            return jsonify(json_list=clouds_d)
    return None

忽略我之前的评论,允许请求生效但所有返回的对象都未定义。

Ignore my previous comment, that allowed the request to work but all the objects returned were undefined.

这就是我的看法最终做到了:

This is how I did it in the end:

clouds_d = dict( (cloud.name, [ photo.to_dict() for photo in cloud.photos ]) for cloud in clouds )
return jsonify(clouds_d)


推荐答案

正如您所发现的,SQLAlchemy模型不是本机的可以序列化为JSON。

As you’ve discovered, SQLAlchemy models are not natively serializable to JSON.

您采用的方法 - 从模型实例的属性手动构造dict - 完成工作,但如果您需要jsonify多个模型,请处理价值转换序列化,或支持反序列化(将JSON转换回SQLAlchemy模型实例),你会发现自己编写了大量繁琐的代码。

The approach you adopted - to manually construct a dict from your model instance’s properties - gets the job done, but if you need to jsonify multiple models, deal with value conversions on serialization, or support deserialization (converting JSON back to a SQLAlchemy model instance) you’ll find yourself writing a lot of tedious code.

更好的解决方案是使用序列化SQLAlchemy的/ deserialization扩展库,例如 SQLAthanor Marshmallow-SQLAlchemy (完全披露:我是SQLAthanor的作者)。

A better solution is to use a serialization/deserialization extension library for SQLAlchemy, such as either SQLAthanor or Marshmallow-SQLAlchemy (full disclosure: I am the author of SQLAthanor).

使用这些库中的任何一个,您基本上可以将SQLAlchemy模型序列化和反序列化为其他格式,或者将它们反序列化为SQLAlchemy模型实例。

Using either of these libraries, you can basically serialize and deserialize SQLAlchemy models to other formats or deserialize them back into SQLAlchemy model instances.

对于SQLAthanor,您可以基本上得到使用一个方法调用完成的工作:

In the case of SQLAthanor, you can basically get the job done with one method call:

json_result = model_instance.dump_to_json()

或(使用更多配置可以提供更精细的控制):

or (with some more configuration that gives you more fine-grained control):

json_result = model_instance.to_json()

您还可以序列化为dict ,或YAML或CSV。

You can also serialize to dict, or YAML, or CSV.

相反的过程是:

model_instance = ModelClass.new_from_json(json_result)

希望这会有所帮助!

这篇关于如何从sqlalchemy中对象进行jsonify?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆