首页 文章

GAE python27返回嵌套的json

提问于
浏览
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...
]

我想要得到的是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 回答

  • 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)
    
  • 0

    这似乎有点hackish,但它的确有效 . 如果你知道更好的方法,请告诉我 . 谢谢 .

    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))
    

相关问题