两台计算机在同一浏览器版本(chrome 58.0.3029.110(64位))上运行Flask版本0.12.2。
这是传递给jsonify函数序列化数据的数据示例:
[('Code1', ['website1.com']), ('Code2', ['website2.com'])]
没有安装simplejson的机器的输出是:
[["Code1",["website1.com"]],["Code2",["website2.com"]]]
与安装simplejson的对比:
[{"code":"Code1",place:["website1.com"]},{"code":"Code2",place:["website2.com"]}]
from flask import jsonify, Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost:5432/test_db'
db = SQLAlchemy(app)
class myModel(db.Model):
__tablename__ = 'testtable'
code1 = db.Column(db.Text, primary_key=True)
code2 = db.Column(db.Text)
def __init__(self, co1, co2):
self.code1 = co1
self.code2 = co2
@app.route("/")
def b():
a = [('Code1', ['website1.com']), ('Code2', ['website2.com'])]
myModel = test_model.myModel("website1.com", "website2.com")
myModel = test_model.myModel("website3.com", "website4.com")
db.session.add(myModel)
db.session.commit()
query = test_model.myModel.query.with_entities(test_model.myModel.code1).all()
print("my model", query, type(query))
foo = jsonify(query)
print(foo)
return foo
if __name__ == "__main__":
app.run(debug=True)
在未安装simplejson的情况下运行python test_file.py
时输出为
[
[
"website3.com"
],
[
"website3.com"
],
[
"website3.com"
],
[
"website3.com"
],
[
"website3.com"
],
[
"website3.com"
]
]
在安装simplejson的情况下运行输出
[
{
"code1": "website3.com"
},
{
"code1": "website3.com"
},
{
"code1": "website3.com"
},
{
"code1": "website3.com"
},
{
"code1": "website3.com"
},
{
"code1": "website3.com"
},
{
"code1": "website3.com"
}
]
总而言之,这可能是关于simplejson和flask-sqlalchemy之间的互动吗?刚刚用烧瓶发生了它
答案 0 :(得分:1)
问题是在运行ubuntu的机器上安装了simplejson python包。它会覆盖python json库,导致它在调用jsonify时返回一个对象数组而不是预期的数组数组。