1

I need to use request package to use API. The API from IT takes a JSON string which look exactly like this:

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

I have a DF frame (image) and I am 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

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
  • Seems like you are not getting a successful response (2xx) from the web service. Try printing `r.status_code`. – Bigya Pradhan Jul 19 '22 at 09:12
  • Sorry. I understand now. This really depends on the implementation on the server side. But `requests.post` for python has a parameter `json` where you can send the data itself without having to use `json.dumps`. Refer to link: https://requests.readthedocs.io/en/latest/user/quickstart/#more-complicated-post-requests – Bigya Pradhan Jul 20 '22 at 09:52

1 Answers1

0

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)
Bigya Pradhan
  • 216
  • 1
  • 7