我正在嘗試使用Python將一些查詢自動化爲一個API。問題在於請求需要以特殊的方式創建,而我只是無法使其工作。這是我在創建時遇到的問題的一部分。Python使用創建一個字符串並在json請求中發送它
payload = "{\n \"filter\": {\n \"name\":[\"name1\", \"name2\"]\n }"
其中name1和name2是可變的,並且是從列表創建的。我試圖做到這一點只是先創建一個函數來創建
[\"name1\", \"name2\"]
這是函數
def create_string(list_of_names):
#Creates the string of line items we want data from
start = '[\\"%s\\"' % list_of_names[0]
for i in list_of_names[1 : ]:
start += ', \\"%s\\"' %(i)
start += "]"
return start
list_of_names = ['name1', 'name2']
然後只用%s零件將其添加到字符串。
payload = "{\n \"filter\": {\n \"name\":%s\n }" % create_string(list_of_names)
這不起作用,我可以認爲這與\是如何在Python中使用有關。
create_string函數創建不同的輸出依賴,如果我打印或不打印。
a = create_string(list_of_names)
print(a)
創建我需要用%s
[\"name1\", \"name2\", \"name3\"]
而只是輸出
'[\\"name1\\", \\"name2\\", \\"name3\\"]'
所以我的問題是,那麼如何通過打印(一)部分傳遞字符串到有效載荷字符串中。有沒有人有這樣的解決方案?
你有一個不使用json模塊的好理由:'import json; str = json.dumps({'filter':{'name':list_of_names}})' –