2016-04-26 117 views
1

返回2个JSON响应我已经蟒蛇瓶返回2个响应如何通过追加蟒蛇烧瓶

response1 = jsonify(teachers=teachers) 
{ 
     "teachers" : [ 
      { 
       "name":"Mary" 
      } 
     ] 
} 
response2 = jsonify(students=students) 
    { 
     "students" : [ 
      { 
       "name":"John" 
      } 
     ] 
} 

怎样才可以有它结合这2的响应?输出应该看起来像:

{ 
     "college" :[ 
     "teachers" : [ 
      { 
       "name":"Mary" 
      } 
     ], 
     "students" : [ 
      { 
       "name":"John" 
      } 
     ] 
} 

我尝试使用response = response1 + response2并追加。

回答

1
# Assuming response1 and response2 are the return value from jsonify 
resp1 = flask.json.loads(response1.data) 
resp2 = flask.json.loads(response2.data)  

resp1.update(resp2) 

OR

import itertools 
response = dict(itertools.chain(resp1.items(), resp2.items())) 
+0

这两个给我的错误'类型错误:“响应”对象不是可迭代' – aaj

+0

如果您有权访问数据,并可以让它进入前的字典调用jsonify(因为它返回一个Response对象),这是最好的。 – Richard

+0

否则你可以使用flask.json.loads - 我已经更新了我的回答,以反映这一点,因为这是你在原始问题中提出的内容,但正如我之前所说的,希望你在访问实际数据之前能够访问它响应对象。 – Richard

-1
user_info = json.loads(user_info.content) 
user_quota = json.loads(user_quota.content) 
user_info['user_quota'] = user_quota 
jsonify(user_info) 
+0

尽管此代码可能会回答问题,但提供有关如何解决问题和/或为何解决问题的其他上下文会提高答案的长期价值。 – Badacadabra