Here是jquery ui自动完成所需的示例json回复。看起来我的情况只需要label
和value
。
我有以下代码:
class City(db.Model):
'''Storage for cities ids.
Index
key_name: id of the city
parent: Country of the city
'''
city_name = db.StringProperty()
term = self.request.get('term')
query = City.all()
query.filter('city_name >=', term)
query.filter('city_name <=', unicode(term) + u"\ufffd")
cities = query.fetch(20, 0)
如何将结果格式化为json,格式如value = city_name,id = key_name?
我也在某处看过以下代码,但它对我不起作用:
map(lambda x: x.city_name(), cities)
答案 0 :(得分:2)
您可以使用django.utils中包含的simplejson:
from django.utils import simplejson as json
然后创建一个字典数组并对其进行json编码:
city_array = []
for city in cities:
city_array.append({'value': city.city_name,
'label': city.city_name,
'id': city.key().name()})
json_message = json.dumps(city_array)