【问题标题】:How to add multiple responses into a single json object如何将多个响应添加到单个 json 对象中
【发布时间】:2019-05-15 02:16:57
【问题描述】:

我正在从我的烧瓶 api 向另一个站点发出一些请求。基本上我的烧瓶 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,我请求另一个 url 来获取他们的所有详细信息。响应为 json 格式。但是,我只得到了上面代码的最后一个响应。我做了类似j==1 之类的操作,因为我想检查退货。

dictToSend[key]=tempDict
return jsonify(dictToSend)

关键是公司 ID,这样我就可以识别工人来自哪个公司。

如何连接所有 json 响应并在最后添加一个类似 "5":{concatenation of all json requests} 的键

谢谢,

【问题讨论】:

    标签: python json flask


    【解决方案1】:

    你的 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
    

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2018-09-29
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多