【问题标题】:Python/Flask - How do I return a valid JSON in a response instead of a String? [duplicate]Python/Flask - 如何在响应中返回有效的 JSON 而不是字符串? [复制]
【发布时间】:2019-07-03 17:27:42
【问题描述】:

我正在使用 Flask Restful 创建一个简单的 API,它在获取响应中返回 JSON。 我所有的方法都很好,我的问题是在响应结果中有点细节,因为 JSON 实际上是作为一个字符串来的,我不明白我需要做什么。

当我使用 json.dumps() 转换 python dict 时会出现问题

我尝试在不使用 json.dumps() 方法的情况下执行此操作,结果以所需的格式出现,但不是实际有效的 JSON。

这是我的代码:

class People(Resource):
def get(self):
    handle =  open("json_test.txt", "r")
    txt = handle.read()
    json  = self.names(txt)
    return jsonify({'result': json})

    def names(self, data):
        json.loads(data)
        print(data)
        ids = []
        names = []
        for n in data['people']:
            print(n)
            id = n['id']
            name = n['name']
            ids.append(id)
            names.append(name)

        test_list = []
        counter = 0
        for item in names:
            test_item = {"id": ids[counter], "name": names[counter]}
            test_list.append(test_item)
            counter = counter+1

        names_json = json.dumps(test_list, ensure_ascii=False)
        print(names_json)
        return names_json

这是我想要的输出:

{
  "result": {
    "people": [
      {
        "id": "12345",
        "nome": "Felipe"
      },
      {
        "id": "54321",
        "nome": "Jean"
      }
    ]
  }
}

但我得到了这个实际输出:

{
result: "{"people": [{"id": "54321", "name": "Felipe"}, {"id": "12345", "name": "Jean"}]}"
}

它来了:result = "{json}",一个字符串而不是实际的 json,但是双引号内的数据是一个有效的 json。

【问题讨论】:

    标签: python json flask flask-restful


    【解决方案1】:

    这行得通吗?

    return names_json["result"]
    

    【讨论】:

    • 不,这就像结果中的数据变成了字符串而不是字典/列表。当我尝试删除 return jsonify({'result': json}) 行时: return jsonify(json) 它给了我一个破碎的 json 用 \ 分隔每个值。
    猜你喜欢
    • 2019-03-12
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多