GAE python27返回嵌套的json

时间:2017-04-26 20:51:40

标签: json google-app-engine gae-python27

这似乎是一项如此简单的任务,但却让我无法实现......

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 docs,python27 docs,没有快乐,并且用这个太多时间烧了。关于这个主题,我在很多相关的SO帖子中得到了这么多。提前谢谢。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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))