TransWikia.com

conversion of dictionary to json to be sent to requests.post

Data Science Asked on August 25, 2021

I have a data frame like this.

df=pd.DataFrame({'sub1':[10,20,30,40],'sub2':[5,10,15,20],'sub3':[1,2,3,4]})

and a dictionary like this.

stud={}
stud['name']="abc"
stud['id'] ="AB10"
stud['address']="some_address"

I convert that data frame to dictionary and combine with the stud dictionary.I wrote the following code.Then this stud dictionary should be made in a json format and sent as a web service.

stud={}
stud['name']="abc"
stud['id'] ="AB10"
stud['address']="some_address"
for i in range(0,len(df)):
   data_sample={}
   data_sample_row=df.iloc[i]
   a=data_sample_row.to_dict()
   stud['data_sample']=a
   str_details=str(stud)

I would like to get the result as shown below.

"{'name':'abc','id':'AB10','address':'some_address','data_sample':{'sub1':10,'sub2':5,'sub3':1}}"
"{'name':'abc','id':'AB10','address':'some_address','data_sample':{'sub1':20,'sub2':10,'sub3':2}}"
"{'name':'abc','id':'AB10','address':'some_address','data_sample':{'sub1':30,'sub2':15,'sub3': 3}}"
"{'name':'abc','id':'AB10','address':'some_address','data_sample':{'sub1': 40,'sub2':20,'sub3': 4}}"

I would like to send this as a parameter in requests.post as following.

response=requests.post(url="some_url",data=str_details)

If I don’t convert to string, gives me an error,
JSONDecodeError: Expecting value: line 2 column 1 (char 1)
If I pass json=str_details, as argument gives me the same error, How to resolve this and get the desired results.

One Answer

To build your data use sth like:

import copy, json

def make_objects(ref_obj, df):
    objects = []
    for i in range(len(df[df.columns[0]].values)):
        cobj = copy.deepcopy(ref_obj)
        cobj['data_sample'] = {}
        for col in df:
            cobj['data_sample'][col] = int(df[col].values[i]) if df[col].dtype == np.int64 else (float(df[col].values[i]) if df[col].dtype == np.float64 else df[col].values[i])
        objects.append(cobj)
    return objects
    
df = pd.DataFrame({'sub1':[10,20,30,40],'sub2':[5,10,15,20],'sub3':[1,2,3,4]})
objects = make_objects({'name':"abc",'id':"AB10",'address':"some_address"}, df)
# in case you want to json-encode the returned objects
json_output = json.dumps(objects)
            

Correct answer by Nikos M. on August 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP