GAE python27 return 嵌套 json

GAE python27 return nested json

这似乎是一项如此简单的任务,但它让我望而却步...

class ViewAllDogs(webapp2.RequestHandler):
    """ Returns an array of json objects representing all dogs. """
    def get(self):
        query = Dog.query()
        results = query.fetch(limit = MAX_DOGS)   # 100
        aList = []
        for match in results:
            aList.append({'id': match.id, 'name': match.name,
                           'owner': match.owner, arrival_date':match.arrival_date})
            aList.append({'departure_history':{'departure_date': match.departure_date,
                          'departed_dog': match.departed_dog}})
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(aList))

以上,我迄今为止最好的约会尝试,让我:

[
  {
    "arrival_date": null,
    "id": "a link to self",
    "owner": 354773,
    "name": "Rover"
  },
  {
    "departure_history": {
      "departed_dog": "Jake",
      "departure_date": 04/24/2017
    }
  },

 # json array of objects continues...
]

我想要得到的是 departure_history 嵌套:

[
  {
    "id": "a link to self...",
    "owner": 354773,
    "name": "Rover",
    "departure_history": {
      "departed_dog": "Jake",
      "departure_date": 04/24/2017
      },
    "arrival_date": 04/25/2017,
  },

# json array of objects continues...
]

我尝试了很多不同的组合,查看了 json 文档,python27 文档,没有任何乐趣,为此浪费了太多时间。我通过许多关于该主题的相关 SO 帖子走到了这一步。提前致谢。

这似乎有点老套,但它确实有效。如果您知道更好的方法,请务必告诉我。谢谢

 class ViewAllDogs(webapp2.RequestHandler):
        """ Returns an array of json objects representing all dogs. """
        def get(self):
            query = Dog.query()
            results = query.fetch(limit = MAX_DOGS)   # 100
            aList = []
            i = 0
            for match in results:
                aList.append({'id': match.id, 'name': match.name,
                               'owner': match.owner, arrival_date':match.arrival_date})
                aList[i]['departure_history'] = ({'departure_history':{'departure_date': match.departure_date,
                              'departed_dog': match.departed_dog}})
             i += 1
            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(aList))

你可以稍微简化一下:

        aList = []
        for match in results:
            aDog = {'id': match.id, 
                    'name': match.name, 
                    'owner': match.owner, 
                    'arrival_date':match.arrival_date,
                    'departure_history': {
                        'departure_date': match.departure_date,
                        'departed_dog': match.departed_dog}
                   }
            aList.append(aDog)