尝试从我的服务器构建JSON响应时遇到问题。
我想获得一个包含其他JSON对象的JSON对象,这些对象是我从SQL查询中获得的,因此我可以通过我的websocket服务器发送包含JSON的文件
直到现在我尝试过这样的事情:
def screenColor(self,ne_Lat, ne_Lng, sw_lat, sw_Lng):
data={}
allData=[]
for rec in self.c.execute('''SELECT * FROM squares WHERE ((lat BETWEEN ? AND ?) AND (long BETWEEN ? AND ?)) ''',(sw_lat, ne_Lat, sw_Lng, ne_Lng)):
data['color']=rec[3]
data['lat']=rec[1]
data['lng']=rec[2]
json_data=json.dumps(data)
allData.append(json_data)
return allData
当我打印返回的值时,我得到:
['{"color": 85, "lat": 31.776879500000156, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.778179500000157, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.779479500000157, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.780779500000158, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.782079500000158, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.78337950000016, "lng": 35.21187200000153}', '{"color": 26, "lat": 31.78467950000016, "lng": 35.21187200000153}', '{"color": 28, "lat": 31.78597950000016, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.78727950000016, "lng": 35.21187200000153}', '{"color": 85, "lat": 31.776879500000156, "lng": 35.21367200000153}', '{"color": 28, "lat": 31.778179500000157, "lng": 35.21367200000153}', '{"color": 85, "lat": 31.779479500000157, "lng": 35.21367200000153}', '{"color": 26, "lat": 31.780779500000158, "lng": 35.21367200000153}', '{"color": 26, "lat": 31.782079500000158, "lng": 35.21367200000153}', '{"color": 26, "lat": 31.78337950000016, "lng": 35.21367200000153}', '{"color": 85, "lat": 31.78467950000016, "lng": 35.21367200000153}
是否有办法将此数组作为JSON对象?那已经是JSON对象吗?
非常感谢!
答案 0 :(得分:1)
您应该尝试以下方法:
def screenColor(self,ne_Lat, ne_Lng, sw_lat, sw_Lng):
allData=[]
for rec in self.c.execute('''SELECT * FROM squares WHERE ((lat BETWEEN ? AND ?) AND (long BETWEEN ? AND ?)) ''',(sw_lat, ne_Lat, sw_Lng, ne_Lng)):
data = {}
data['color']=rec[3]
data['lat']=rec[1]
data['lng']=rec[2]
allData.append(data)
return json.dumps(allData)
否则,如果你在循环之外定义你的字典data
,它会在每次迭代时被覆盖我猜...