【问题标题】:How to return JSON objects (List of Dictionaries) in Flask API如何在 Flask API 中返回 JSON 对象(字典列表)
【发布时间】:2019-07-10 17:13:24
【问题描述】:

这里是新手,坚持将一些对象从 JSON 返回到我的 Flask API。

我有一个名为 data 的字典列表,您将在下面的代码中看到。我需要检查 status_id 是否在数据中。如果是,我必须显示该用户的名称。我如何从列表中访问字典?还是我的 json 无效?我确实使用了 linter 进行检查,它通过了 JSON 测试。我收到错误:字符串索引必须是整数。这让我相信,因为它是一个列表,所以我需要整数作为索引。

对正确方向的任何帮助都会很棒。

这是我的代码:

@app.route("/status/<status_id>", methods=['GET'])
def get_status(status_id):
    data = [{
                "id": 5,
                "name": "Meghan"
            },
            {
                "id": 6,
                "name": "Julia"
            }
        ]

    data_dump = json.dumps(data, indent=4)

    if status_id in data_dump:
        #find that status id and name and return it
        return data_dump[status_id]['name']
    else:
        return "Not Found in Dictionary"

【问题讨论】:

  • json.dumpsdata 转换为str 以json 形式表示您的dict。使用data 进行比较逻辑(因为datadict)而不是data_dump(这是str)。
  • 另外你的data不包含密钥'status_id',你的意思是return data_dump[status_id]['name']吗?

标签: python python-3.x api flask flask-restful


【解决方案1】:

见下文。 get_status 函数的简化版本。

注意HTTP状态码(200 Vs. 404)

@app.route("/status/<status_id>", methods=['GET'])
def get_status(status_id):
    data = [{
        "id": 5,
        "name": "Meghan"
    },
        {
            "id": 6,
            "name": "Julia"
        }
    ]
    name = None
    for entry in data:
        if entry['id'] == status_id:
            name = entry['name']
            break
    if name is not None:
        print('The name for status_id {} is {}'.format(status_id,name))
        return name, 200
        # or, if you want to return both use Flask jsonify and send a dict
        # see http://flask.pocoo.org/docs/1.0/api/#flask.json.jsonify
    else:
        print('Can not find a name for status id {}'.format(status_id))
        return "Not Found in Dictionary", 404

【讨论】:

  • 嗨!我喜欢你的简化版,但在转到http://127.0.0.1:5000/status/5 时会收到"Not Found in Dictionary", 404
  • @newcoder 我添加了调试打印,可以帮助您查看发生了什么。查看更新的代码。
  • k,感谢您的调试语句。我收到了Can not find a name for status id 5,仍在单步执行我的代码。
  • 当我这样做时:if entry['id'] == 5: 它显示正确的输出
  • k,这行得通:if entry['id'] == int(status_id): 感谢您的帮助!我会把你的答案标记为正确的。
【解决方案2】:

对我来说,您似乎想返回 id == status_id 所在的对象的名称。是对的吗?比你不必将它转储到 json。您可以检查status_id 是否存在于列表中:

len(list(filter(lambda x: x['id'] == status_id, data))) == 1

解释:

list(filter(lambda x: x['id'] == status_id, data))

这会过滤您的字典列表,使其仅包含具有匹配 ID 的字典。

len(...) == 1

这会检查是否只有一个对象具有此 ID。如果你想返回那个字典的名字,你可以这样写:

matching_dict = list(filter(lambda x: x['id'] == status_id, data))
if len(matching_dict) == 1:
    return matching_dict[0]['name']

然后,如果您想返回 json(作为字符串)。然后你必须像 json.dumps(matching_dict[0]) 一样调用json.dumps(),这取决于你想做什么。

编辑:所以综合起来可能是这样的:

@app.route("/status/<status_id>", methods=['GET'])
def get_status(status_id):
    data = [{
                "id": 5,
                "name": "Meghan"
            },
            {
                "id": 6,
                "name": "Julia"
            }
        ]

    matching_dict = list(filter(lambda x: x['id'] == status_id, data))
    if len(matching_dict) == 1:
        return json.dumps(matching_dict[0])
    else:
        return "Found zero or more than one in Dictionary"

请求:GET /status/5

回复:{"id":5, "name": "Meghan"}

【讨论】:

  • 好的,谢谢!为了执行 GET 请求,我最终必须在我的 api 中显示每个用户 ID 的 json。那是我使用 json.dumps 的地方吗?
  • 添加了完整的代码。如果要将 dict Python 对象转换为纯字符串,则必须调用 json.dumps。这就是返回结果时最后会发生的事情。
  • 好的,谢谢!当我转到http://127.0.0.1:5000/status/5 时,我得到Found zero or more than one in Dictionary
  • L3n95 - 您的代码会遍历 data 中的所有条目。如果数据中有很多条目,这可能会很广泛..
  • @balderman 是的,这是真的。 @newcoder 比您没有匹配的用户或不止一个。您可以打印matching_dict 进行调试
猜你喜欢
  • 2019-09-20
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2018-01-13
相关资源
最近更新 更多