【python】記錄一次python傳送json資料到go服務端,服務端解析失敗問題

alisleepy發表於2024-04-26

【python】記錄一次python傳送json資料到go服務端,服務端解析失敗問題

背景:在做效能測試時,python把採集到的效能資料透過post回傳到服務端,服務端用go實現,服務端是將接收的json透過json.Unmarshal反序列化為對應的結構體,但在實現時一直提示資料型別錯誤的問題

問題程式碼

python傳送請求
dict_data = {a:1, b:2, c:3}   # dict_data是一個字典
headers = {'Content-Type': 'application/json'}
data = json.dumps(dict_data)
response = requests.post(url, json=data, headers=headers)
go接收引數反序列化為結構體
// perfData是結構體,對應的json資料
err := json.Unmarshal(body, &PerfData)
報錯資訊
err1 is : json: cannot unmarshal string into Go value of type dao.PerfData

藉助文心一言,說是資料型別錯誤,然後一直對比檢視json的每個欄位和結構體中的資料型別,發現沒問題

解決

忽然想起來,python中傳送json格式的資料時,會自動將字典轉化為json,無需手動json.dumps轉化為json資料

python正確程式碼
dict_data = {a:1, b:2, c:3}   # dict_data是一個字典
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=dict_data, headers=headers)     # 會自動把dict轉化為json,所以引數還是字典型別

相關文章