0

这似乎是一个如此简单的任务,但它让我难以捉摸......

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...
]

我想要得到的是嵌套的离开历史:

[
  {
    "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 帖子了解了这一点。提前致谢。

4

2 回答 2

2

你可以稍微简化一下:

        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)
于 2017-04-27T15:22:47.630 回答
0

这似乎有点骇人听闻,但它确实有效。如果你知道更好的方法,一定要告诉我。谢谢。

 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))
于 2017-04-26T21:42:23.903 回答