Javascript 如何在Flask后端处理JSON数据的大量输出
我只是想找出解析这个巨大的JSON输出的最有效的方法。当我像对待字典一样对待响应时,会得到一个错误(如下所示)。它将在POST请求中从我的React前端发送到我的Flask服务器 回复请求(我不认为这是问题所在): 烧瓶后端:Javascript 如何在Flask后端处理JSON数据的大量输出,javascript,python,json,reactjs,flask,Javascript,Python,Json,Reactjs,Flask,我只是想找出解析这个巨大的JSON输出的最有效的方法。当我像对待字典一样对待响应时,会得到一个错误(如下所示)。它将在POST请求中从我的React前端发送到我的Flask服务器 回复请求(我不认为这是问题所在): 烧瓶后端: @app.route('/api/prescription', methods=['GET', 'POST']) def prescription(response={}): # POST request if request.method == 'PO
@app.route('/api/prescription', methods=['GET', 'POST'])
def prescription(response={}):
# POST request
if request.method == 'POST':
print('prescription POST request')
response = request.get_json()
print('response: ',response)
x = response['data']['tracks'] <- error
y = response.get('data').get('tracks') <- error
“打印('response:',response')的JSON输出:
这个响应看起来像一个对象,有一个数据的字符串键和一个字符串值,但是你在对它进行索引,就像这个值是一个对象,有一个轨迹键和一个数组值一样。你能用JSON解析'data'的字符串值吗?如前所述,问题在于
response['data']
是一个字符串。要将其解析为对象,可以使用。
结果应该是:
import json
@app.route('/api/prescription', methods=['GET', 'POST'])
def prescription(response={}):
if request.method == 'POST':
response = request.get_json()
data = json.loads(response['data'])
tracks = data['tracks']
是的,调用x=response['data']和x=response.get('data')都有效。那么,在这两种情况下,x都是一个长字符串,而不是一个对象,对吗?我已经有一段时间没有使用python了,但这就是问题所在。因为x是一个字符串,当你调用x['tracks']时它会抛出,它需要一个整数索引。你说得对!它需要一个整数索引。x[i]返回一个字母。那么我该如何解析这些数据呢?我不知道,我还没有用python做过web工作
x = response['data']['tracks']
TypeError: string indices must be integers
response: {'data': '{"tracks":[{"album":
{"album_type":"ALBUM","artists":[{"external_urls":
{"spotify":"https://xyz"},"href":"xyz",
"id":"foijWiojdae","name":"Snail
Mail","type":"artist","uri":
"spotify:artist:4zxWyxyzI8Fq1jWXJJe"}],
"external_urls":{.... etc (much longer)
import json
@app.route('/api/prescription', methods=['GET', 'POST'])
def prescription(response={}):
if request.method == 'POST':
response = request.get_json()
data = json.loads(response['data'])
tracks = data['tracks']