首页 > 解决方案 > 在 Python 中通过 POST 发送 JSON 数组

问题描述

我在 python 上有点菜鸟(刚刚学了一些代码看 Youtube 视频)

我正在尝试做的事情:

[ {
         "locator":"TRANSACAO448",
         "storeCode":"loja01",
         "deviceCode":"teste01",
         "eventDate":"2020-04-01 09:30:53",
         "memberIdentification":"04153883506",
         "employeeIdentification":"",
         "offerCode":"4",
         "points":10,
         "purchaseValue":1,
         "additionalInformation":[
            {
               "key":"CODMOVPON",
               "value":"1"
            }
         ]
      },
      {
         "locator":"TRANSACAO448",
         "storeCode":"loja01",
         "deviceCode":"teste01",
         "eventDate":"2020-04-01 09:30:53",
         "memberIdentification":"04153883506",
         "employeeIdentification":"",
         "offerCode":"4",
         "points":10,
         "purchaseValue":1,
         "additionalInformation":[
            {
               "key":"CODMOVPON",
               "value":"1"
            }
         ]
}]
with open('deposits.json', 'r') as infile:

    # Variable for building our JSON block
    json_block = []

    for line in infile:

        # Add the line to our JSON block
        json_block.append(line)

        # Check whether we closed our JSON block
        if line.startswith('{'):

            # Do something with the JSON dictionary
            json_dict = json.loads(''.join(json_block))
            a = json_dict

            # Start a new block

#Request com os parametros para envio, como tipo e url de destino
r = requests.post(url, data=json.dumps(a) ,headers=headers,timeout=60)
print   "------------------------------------------------------------------------------------"
print  "Request:" 
print   json.dumps(a)
print   "Data_envio:"+data_envio_completa
print  (r)
print  (r.text)
print   "------------------------------------------------------------------------------------"
#salva o resultado em um txt com a data de envio no nome
with open (data_envio+'_log_transacoes.txt','wb') as l:
    l.write(json.dumps(a))
    l.write('Status: '+str(r.status_code))
    l.write(r.text.encode('utf-8'))
json_block = []

问题是: 我需要像 LOP 一样每次发送一个请求,因为这个 API 不接受 [{json},{json}] 仅 {json} 并且像现在这样的代码只发送 1 个请求,不知道有多少JSON文件中有行。

有人可以帮助我吗?

标签: pythonarraysjsonpostpython-requests

解决方案


您可以使用jsonpython 中的包来简化代码

import json

with open('./deposits.json.json') as f:
    json_file = json.load(f)
    print(json_file)

那会让你

[{'locator': 'TRANSACAO448', 'storeCode': 'loja01', 'deviceCode': 'teste01', 'eventDate': '2020-04-01 09:30:53', 'memberIdentification': '04153883506', 'employeeIdentification': '', 'offerCode': '4', 'points': 10, 'purchaseValue': 1, 'additionalInformation': [{'key': 'CODMOVPON', 'value': '1'}]}, {'locator': 'TRANSACAO448', 'storeCode': 'loja01', 'deviceCode': 'teste01', 'eventDate': '2020-04-01 09:30:53', 'memberIdentification': '04153883506', 'employeeIdentification': '', 'offerCode': '4', 'points': 10, 'purchaseValue': 1, 'additionalInformation': [{'key': 'CODMOVPON', 'value': '1'}]}]

加载到您的变量中,该变量是一个 json 数组,然后您可以循环遍历它以{}单独发送每一行

for entry in json_file:

  r = requests.post(url, data=json.dumps(entry) ,headers=headers,timeout=60)


推荐阅读