我正在编写一个API,它查询基于Cassandra 2.1.2的数据库,并以JSON格式返回结果。为此,我使用了cqlengine。
以下是简化的模式:
class Checkins(Model):
Model.__comment__ = "Table mapping for submit datastore"
changelist = columns.Integer (primary_key= True) # Changelist number
checkin_date = columns.DateTime() # Submit time
stream_name = columns.Ascii (primary_key= True) # Stream-name
creator = columns.Ascii () # Creator
我的问题是
clobj = Checkins.objects(changelist=changelist).get()
如何将结果集转换为json格式?
发布于 2015-03-12 20:42:07
您可以从cqlengine 0.12开始创建dictionaries from models。在此基础上,您可以使用json模块获取JSON格式。您必须小心,因为日期时间不是json可序列化的。因此,您需要首先将其转换为字符串(或者查看this question以找到修复datetime序列化问题的其他方法)。
import json
clobj = Checkins.objects(changelist=changelist).get()
clobj_dict = dict(clobj_dict)
clobj_dict['checkin_date'] = str(clobj_dict['checkin_date'])
json_string = json.dumps(clobj_dict)
或者,您可以将其作为属性添加到类中
import json
class Checkins(Model):
# Define your model as before
# ...
@property
def json(self):
# Perform the same thing as before.
json_dict = dict(self)
json_dict['checkin_date'] = str(json_dict['checkin_date'])
return json.dumps(clobj_dict)
# Just call the property.
clobj = Checkins.objects(changelist=changelist).get()
json_string = clobj.json
https://stackoverflow.com/questions/27697904
复制相似问题