如何将多个响应添加到单个json对象中

时间:2019-05-15 02:16:57

标签: python json flask

我正在从我的Flask API向其他站点提出一些请求。基本上我的flask API是代理。因此,最初,我用已知的公司ID替换参数,然后获取所有工作人员ID。给定工人ID,我尝试提出另一个请求,以帮助我获取他们的所有详细信息。但是,使用下面的代码,我只会得到最后的响应,这仅意味着最后一个工作程序的详细信息。您现在可以忽略j == 1,因为我出于测试目的。

tempDict={}
updateDic={}
dictToSend={}
 j=0
#i = companyid

#id=workerid

# I make several calls to url2 depending on the number of employee ids in number

for id in number:
    url2="someurl/" + str(i)+ "/contractors/"+str(id)
                r = requests.get(url2, headers={'Content-type': 'application/json',"Authorization":authenticate,'Accept': 'application/json'})
    print("id"+str(id))
    print(url2)

    loadJsonResponse2=json.loads(r.text)
    print(loadJsonResponse2)
    key = i


    tempDict.update(loadJsonResponse2)
    # I want to have all of their details and add the company number before            

    print(tempDict)

    if(j==1):
        dictToSend[key]=tempDict
        return jsonify(dictToSend)

    j=j+1





     return jsonify(dictToSend)


因此,我拥有所有工作人员ID,并要求其他网址获取其所有详细信息。响应为json格式。但是,我只得到上面的代码的最后响应。我做了类似j==1的操作,因为我想检查退货。

dictToSend[key]=tempDict
return jsonify(dictToSend)

密钥是公司ID,以便我可以识别工人来自哪个公司。

如何连接所有json响应,最后添加诸如"5":{concatenation of all json requests}之类的密钥

谢谢

1 个答案:

答案 0 :(得分:0)

您的json对象密钥是

#i = companyid
.
.
.
 key = i
.
.
.
# You are adding all your responses to companyid,
# better make a key with companyid and workerid
# key = str(companyid) + ":" + str(workerid)
dictToSend[key]=tempDict

还有这里

# you may not need this, since there is already a loop iterating on workerid
if(j==1):
    dictToSend[key]=tempDict
    return jsonify(dictToSend)

j=j+1

# then only useful line would be 
dictToSend[key]=tempDict
相关问题