我有一個字典串列,這些字典正在用另一個串列中的資料動態填充。然后將此字典串列用作請求中的正文引數。字典串列必須是一個字串,請求才能成功。
問題是,當我動態填充字典串列 str(list_of_dicts) 時,它會在字串物件周圍加上雙引號,并在其中的所有內容周圍加上單引號。我需要它正好相反,用雙引號包裹字串,并在里面的所有內容上使用單引號。
我已經嘗試過替換、str、repr、join 和 json.dumps,但都無濟于事。
def insert_header(self, request):
pid = request.meta['pid']
pa = request.meta['pa']
url = request.url
pid = [x.split('ern:product::')[-1] for x in pid]
body = [
{"id":"1234567","variables":{"id":"ern:product::pid"}},
{"id":"1234567","variables":{"id":"ern:product::pid"}},
{"id":"1234567","variables":{"id":"ern:product::pid"}}
]
if len(pid) == len(body):
for counter, i in enumerate(body):
i["variables"] = {"id":"ern:product::" pid[counter]}
body = str(body)
body.replace("'", '"')
return Request(url, method='POST', meta=request.meta, body=body, callback=self.check_header, **self.parse_page_kwargs)
真正令人沮喪的是,在 python shell 中,我可以復制失敗的字典串列(帶引號的串列以錯誤的方式)并執行: list_of_dicts.replace("'", '"') 它回傳正是我需要的, 只是在我運行代碼時并沒有像那樣改變。提前感謝您的任何建議。
uj5u.com熱心網友回復:
我認為您應該洗掉該行body = body[1:-1]。
str(body)不會在開頭和結尾放置任何引號。因此,您正在洗掉部分實際資料。
您也可以使用body = json.dumps(body),無需任何進一步更換。
看實際str使用內容print(body)。它應該看起來像:
[{"id": "1234567", "variables": {"id": "ern:product::pid"}}, {"id": "1234567", "variables": {"id": "ern:product::pid"}}, {"id": "1234567", "variables": {"id": "ern:product::pid"}}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318282.html
上一篇:將主要游戲回圈轉化為功能
