如何在python中通过Google App Engine数据存储获得JSON对象?
我在数据存储中有一个具有以下字段的模型:
id
key_name
object
userid
created
Now I want to get all objects for one user:
query = Model.all().filter('userid', user.user_id())
如何从查询中创建JSON对象以便编写它?
我想通过AJAX调用获取数据。
最佳答案
不确定是否得到了您想要的答案,但您的意思是如何将查询对象中的模型(条目)数据直接解析为JSON对象吗?(至少我一直在找这个)。
I wrote this to parse the entries from Query object into a list of JSON objects:
def gql_json_parser(query_obj):
result = []
for entry in query_obj:
result.append(dict([(p, unicode(getattr(entry, p))) for p in entry.properties()]))
return result
您可以使用simplejson对应用程序进行编码,使其响应AJAX请求,例如:
query_data = MyModel.all()
json_query_data = gql_json_parser(query_data)
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(json_query_data))
你的应用程序将返回如下内容:
[{'property1': 'value1', 'property2': 'value2'}, ...]
如果有帮助,请告诉我!