Pandas df to json - request using

Viewed 41

:)

I need to use request package to use API. Api from IT needs json which look exactly like this:

{ "StoreCode": "7144", "GlovoStoreCode": "7144_1", "ProductList": [ { "GlovoId": "10" }, { "GlovoId": "10" } ] }

I have a df frame (image) and Iam using .to_json function but I cant get result like should be. Could please someone let me knot how to convert my df to result exactly like API needs. Really thanks!

StoreCode   GlovoStoreCode  ProductList

0 4452 4452_1 360908 1 4452 4452_1 125539 2 4452 4452_1 297758 3 4452 4452_1 2025651

DF AND MY REQUEST RESULT

1 Answers

First convert the types to match the request.

df["StoreCode"]=df["StoreCode"].astype(str)
df["GlovoStoreCode"]=df["GlovoStoreCode"].astype(str)

Only performing the transformation for 1st item. Setup a loop if you want to do it for multiple rows.

first_item=df.to_dict(orient="records")[0]
first_item["ProductList"]=[{"GlovoID":i} for i in first_item["GlovoID"]]
del first_item["GlovoID"]
first_item=json.dumps(first_item)
Related