Home > OS >  Use my dataframe in a loop so It can be use in a Json process
Use my dataframe in a loop so It can be use in a Json process

Time:05-04

I have the next code

payload = json.dumps({
  "phones": [
    {
      "phone": "593 999999999"
    },
    {
      "phone": "593 000000000"
    }
  ]
})
headers = {
  'Authorization': 'Bearer ********',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

The responde message I´ts:

`{"summary":{"total":2,"valid":1,"invalid":1},"numbers":[{"valid":true,"error":null,"input":" 593 997178570","phone":" 59399999999","wid":"[email protected]","kind":"mobile","country":"EC","countryPrefix":593,"formats":{"local":"997178570","nationaal":"099 999 9999","international":" 593 99 999 9999"}},{"valid":false,"error":"The phone number is not WhatsApp compatible","input":" 593 000000000","phone":" 593 000000000","wid":null,"kind":"unknown","country":"EC","countryPrefix":593,"formats":{"nationaal":" 593 000000000","international":" 593 000000000"}}]}`

And then I do this.

data = response.json()

aux=pd.DataFrame(data['numbers'])
resultado=aux[['phone','valid']]

So I already know how to put that responde into a dataframe that It´s the purpose of this.

So my question is this, how can I use that process with a dataframe simple as this

Number
593987654321
593987654322
593987654323
593987654324

It´s there a way to put that dataframe into a loop so I can use my Json process. Or to convert my dataframe into a dictionary?. I have no experience working with Json.

CodePudding user response:

IUUC, you can export Number column to list of dictionaries with .to_dict('records').

payload = {"phones": df[['Number']].rename(columns={'Number':'phone'}).to_dict('records')}
print(payload)

{'phones': [{'phone': 593987654321}, {'phone': 593987654322}, {'phone': 593987654323}, {'phone': 593987654324}]}
  • Related