首页 > 解决方案 > Flask 将一些响应对象作为类似字符串的 JSON 而不是 JSON 返回

问题描述

我试图从烧瓶路线返回五个变量。似乎无论我如何格式化它们,它们中的两个除了看起来像 JSON 的字符串之外不会返回任何东西。

我的烧瓶路线看起来像这样

@app.route('/mapcreator/<lat>/<lng>', methods=['GET', 'POST'])
def receive_coords(lat, lng):
    lat = float(lat)
    lng = float(lng)
    point = (lat,lng)
    map1 = somefunction(point)
    number = ((somefunction(point))[0])
    featureCount = ((somefunction(point))[1])
    map2 = ((amb.somefunction(point))[2])
    response = make_response(jsonify(map1=map1, number=number, featureCount=featureCount, map2=map2, point=point))
    response.headers['content-type'] = 'application/json'
    return response

number、point、map1 作为 json 对象正确返回。Python中每个变量的类型:

这是在后端处理每个变量的方式:

看起来像标准的geojson

看起来像一个标准的 json

如果我将这些类型更改为 dict,我会得到

500内部服务器错误。

就目前而言,他们像这样登录浏览器控制台:

featureCount:"{"parking":67,"bicycle_parking":32,"bench":20,"p.....

map2:"{"type": "FeatureCollection", "features": [{"geometry": {"type": "Point", "coo.....

它们不读作“Object >”,而是读作类似 JSON 的字符串。

我在这里尝试了一切,我真的很难过。我看不出这两个响应对象有什么不同,我无法让它们成为真正的 JSON 响应。

提前一百万谢谢!

标签: pythonjsonflask

解决方案


我解决了这个问题。

response = make_response(jsonify(map1=map1, number=number, 
featureCount=json.loads(featureCount), 
map2=json.loads(map2), point=point))

不得不与 jsons 是 json 像字符串而不是 JSON 对象有关。Pandas 只创建 json 样式的字符串。


推荐阅读