首页 > 解决方案 > GET 请求 - 计数

问题描述

我正在尝试在 Python 中获取剧集对象中评论对象的计数。我已经尝试了几天:包括示例。但我无法让它工作。我要做的是首先找到剧集对象,每次找到评论时,计数器都会增加 1。

数据集:

{
      "_id": "5df808570a83c1af4da13230", 
      "airdate": "2017-11-02", 
      "airtime": "20:30", 
      "image": "http://static.tvmaze.com/uploads/images/original_untouched/133/334409.jpg", 
      "name": "Derek", 
      "number": 8, 
      "reviews": [
        {
          "_id": "5dfc548b759dd951ac61ab6e", 
          "comment": "koijoij", 
          "rating": "2 stars", 
          "username": "k"
        }, 
        {
          "_id": "5dfc551852101d027d229e0a", 
          "comment": "hiki", 
          "rating": "3 stars", 
          "username": "jk"
        }
      ], 
      "runtime": 30, 
      "season": 2, 
      "summary": "Janet creates a big problem for Michael. Meanwhile, Eleanor lets Chidi in on a secret, and Jason puts Tahani in a difficult position.", 
      "url": "http://www.tvmaze.com/episodes/1215818/the-good-place-2x08-derek"
    }

蟒蛇方法:

@app.route("/api/v1.0/episodes/<string:episode_id>/pageCounterReviews", methods=["GET"])
def getPageCountReview(episode_id):
    count=0;

    episode = episodes.find_one({"_id":ObjectId(episode_id)},{"reviews":1,"_id":0})
    for review in episode["reviews"]:
        count=count+1;

        return make_response(jsonify(count), 200)

标签: python

解决方案


您可以使用len

>>> data = {"reviews": [{"_id": "1"}, {"_id": "2"}]}
>>> print(len(data['reviews']))
2

推荐阅读