Automate get from a list of tuples to JSON variables

Asked

Viewed 83 times

0

I have a code that searches for information in a list of tuple, the code is very simple, it is searching the info in Index [0] and putting in my variables for the POST. I’d need to automate it so he can process all the items on the list until it’s over. Does anyone have any idea how I might do ? What confuses me most is because of the mapping of the indices, how I fit this into a 'for' or 'While' for the code to understand that it needs to do this until I finish the tuples of my list ?

I’m putting the code and photo of my dynamodb with my first post using this code.

import requests

#aqui está minha lista de tuplas
lista = [(1, 'ADMINISTRADOR', 'ADMIN'), (2, 'CEO', 'USER'), (3, 'ALEATÓRIO', 'USER')]

#aqui busco o primeiro valor da minha tupla
id_user = lista[0][0]
nome_user = lista[0][1]
tipo_user = lista[0][2]

#aqui começo a montar o JSON para o post
payload = {
            "id": id_user,
            "nome": nome_user,
            "usuario": tipo_user

            }
try:
    #ENVINDO POST PARA API
    url = 'https://lssy4bswv8.execute-api.us-east-2.amazonaws.com/dev/gravar'
    print('URL API Post: ', url)
    headers = {
              "Content-Type": "application/json",
              'Accept': 'application/json'
          }
    response = requests.post(url, json=payload, headers=headers)
finally:
    print('FINISH')

inserir a descrição da imagem aqui

1 answer

1

I practically solved my problem with a bow tie. I always pick the position 0 from my list but at the end of the script I delete the index 0, IE, my code picks the new index 0 that before was 1 until it ends.

import requests

Here’s my list of tuples

lista = [(1, 'ADMINISTRADOR', 'ADMIN'), (2, 'CEO', 'USER'), (3, 'ALEATÓRIO', 'USER')]

Here I look for the first value of my tuple

cont = len(lista)

while cont > 0:

    id_user = lista[0][0]
    nome_user = lista[0][1]
    tipo_user = lista[0][2]


    #aqui começo a montar o JSON para o post
    payload = {
            "id": id_user,
            "nome": nome_user,
            "usuario": tipo_user
                }

    try:
        #ENVINDO POST PARA API
        url = 'https://lssy4bswv8.execute-api.us-east-2.amazonaws.com/dev/gravar'
        print('URL API Post: ', url)
        headers = {
                  "Content-Type": "application/json",
                  'Accept': 'application/json'
              }
        response = requests.post(url, json=payload, headers=headers)
    finally:
        print('FINISH')

    lista.pop(0)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.