-1

I'm kinda noob at python (just learned a few codes watching Youtube videos)

What I'm trying to do:

  • I have a file named deposits.json with multiple JSON, like bellow
[ {
         "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"
            }
         ]
}]
  • Have the script bellow that send post to an intern API
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 = []

Issue is: I need to send one request per time like a LOP because this API don't accept [{json},{json}] only {json} and the code like is right now only send 1 request, doesnt metter how many lines there is in JSON file.

Can somebody help me?

azro
  • 53,056
  • 7
  • 34
  • 70
  • 1
    You can replace your entire `with open()` block to `json.load('deposits.json')`. You can then iterate over the objects inside of the returned list. – jordanm Apr 02 '20 at 20:52
  • 2
    @jordanm `json.load` expects a file descriptor, so the `with open` block is still necessary, but can be a single line: `json.load(infile)` – DeepSpace Apr 02 '20 at 20:56
  • 2
    Does this answer your question? [Post JSON using Python Requests](https://stackoverflow.com/questions/9733638/post-json-using-python-requests) – αԋɱҽԃ αмєяιcαη Apr 03 '20 at 03:08

1 Answers1

2

You could simplify your code using json package in python

import json

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

that would get you

[{'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'}]}]

loaded in your variable which is an array of jsons, you could then loop over it to get each {} row sent alone

for entry in json_file:

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

kareem_emad
  • 1,123
  • 1
  • 7
  • 12
  • That count as [duplicated](https://stackoverflow.com/questions/9733638/post-json-using-python-requests) question, we aren't supposed to answer dupe questions. – αԋɱҽԃ αмєяιcαη Apr 03 '20 at 03:08
  • I agree that could be a duplicate, but I don't think it's the same as the one you mentioning is different, its total focus is on malformed requests while this one 's main problem was with loading json data from disk and chunking it properly – kareem_emad Apr 03 '20 at 03:46
  • `loading` or `dumping` `JSON` is completely asked multiple times, if the `OP` made a little search on the community, he will get a a bulk of answers towards that. – αԋɱҽԃ αмєяιcαη Apr 03 '20 at 03:51
  • It works perfectly!!! @Kareem, thank you very much my friend! – Gabriel Diniz Apr 03 '20 at 23:00