如何替换JSON文件中的值并将其附加到Response

时间:2020-07-22 09:25:02

标签: python json

我有一个这样的JSON文件。

{
   "Get_Request_1": {
      "FindRequest": {
         "CompanyIdentifiers_typehint": [
            "CompanyIdentifiers"
         ],
         "CompanyIdentifiers": [
            {
               "RIC": {
                  "Value": "MSFT.O"
               }
            }
         ],
      }
   }
}

我正在使用以下功能通过API调用获取数据:

def RetrieveQuotes(token, appid):
    quoteRequestMsg = json.load(open('Get_Request_1.json'))
    
    quoteURL = 'http://api.abcd.com/api/Developments/Developments.svc/REST/Developments_1/Developments_1'
    headers = {'content-type': 'application/json;charset=utf-8',
               'ApplicationID': appid, 'Token': token}
    quoteResult = doSendRequest(quoteURL, quoteRequestMsg, headers)
    if quoteResult and quoteResult.status_code == 200:
        print('Quote response message: ')
        #print(quoteResult.json())
        #print(json.dumps(quoteResult.json(), sort_keys=True,indent=2, separators=(',', ':')))
    with open('quoteResult.json', 'w') as f:
        json.dump(quoteResult.text,f)

上面的脚本运行正常。现在我有5家公司需要为其提取数据。数据值存在于数据框中。

import pandas as pd
df = pd.read_excel('Company_List.xlsx')
print(df)

          Company Name Ticker
0    Microsoft Corp    MSFT.O
1             ABB Ltd.   ABBN
2  Abbott Laboratories  ABT.N
3          AbbVie Inc.   ABBV
4        Accenture plc  ACN.N

如何遍历df['Ticker']并将其附加到结果响应JSON。 我是python的新手,正在逐步学习这些东西。我尝试了以下方法。

def RetrieveQuotes(token, appid):
    quoteRequestM

    sg = {
       "Get_Request_1": {
          "FindRequest": {
             "CompanyIdentifiers_typehint": [
                "CompanyIdentifiers"
             ],
             "CompanyIdentifiers": [
                {
                   "RIC": {
                      "Value": "MSFT.O"
                   }
                }
             ],
          }
       }
    }
        
        quoteURL = 'http://api.abcd.com/api/Developments/Developments.svc/REST/Developments_1/Get_Developments_1'
        headers = {'content-type': 'application/json;charset=utf-8',
                   'ApplicationID': appid, 'Token': token}
        print('############### Sending Quote request message to TRKD ###############')
        import pandas as pd
        df = pd.read_excel('Company_List.xlsx')
        for i in df['Ticker']:
            tmp=i
            quoteRequestMsg["Get_Request_1"]["FindRequest"]["CompanyIdentifiers"][0]['RIC']=tmp
            quoteResult = doSendRequest(quoteURL, quoteRequestMsg, headers)
            #print(quoteResult)
            quoteResult.append(quoteResult)
            if quoteResult and quoteResult.status_code == 200:
                print('Quote response message: ')
                #print(quoteResult.json())
                #print(json.dumps(quoteResult.json(), sort_keys=True,indent=2, separators=(',', ':')))
            with open('quoteResult.json', 'w') as f:
                json.dump(quoteResult.text,f)

0 个答案:

没有答案