我在將通過腳本構建的字符串轉換爲JSON對象時遇到了一些麻煩(我試圖構建發佈數據以發出發佈請求API端點)。難以將字符串轉換爲JSON對象以便對其進行urlencode
,我發現了以下錯誤:
bos-mpqpu:config_parse rabdelaz$ python3 lexparse.py
{"__class__":"HttpTestClient","description":"CP Codes","url":"://","serverip":"","method":"GET","enabled":true,"headers":[],"tests":[],"purge":false,"procs":[]}
Traceback (most recent call last):
File "lexparse.py", line 448, in <module>
print(ast.literal_eval(test_case_ACT_template.substitute({'protocol': "",'host': "", 'path' : "", 'query' : "", 'serverip' : "", 'tests' : ""})))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 85, in literal_eval
return _convert(node_or_string)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 66, in _convert
in zip(node.keys, node.values))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 65, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 84, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x103c50c18>
這裏是產生上述代碼:
test_case_ACT_template = Template('{"__class__":"HttpTestClient","description":"CP Codes","url":"$protocol://$host$path$query","serverip":"$serverip","method":"GET","enabled":true,"headers":[],"tests":[$tests],"purge":false,"procs":[]}')
print(test_case_ACT_template.substitute({'protocol': "",'host': "", 'path' : "", 'query' : "", 'serverip' : "", 'tests' : ""}))
print(ast.literal_eval(test_case_ACT_template.substitute({'protocol': "",'host': "", 'path' : "", 'query' : "", 'serverip' : "", 'tests' : ""})))
注意,第一個print語句導致輸出線與{"__class__"
開始
我的總體目標是urlencode我的json字符串,但一些搜索SO導致我相信我應該先做在對它進行編碼之前,請使用210。
的最終目標是這樣的:
form_data = {'name' : 'CP Code Demo', 'configfilename' : '1-DR4E2_kona-ion.aws-eu-ssl.template_pm-2', 'type' : 'json', 'script' : urlencode(json.load(post_data))}
凡post_data
是一系列模板替換。
原來的錯誤,導致我開始尋找到ast.literal_eval如下:
Traceback (most recent call last):
File "lexparse.py", line 521, in <module>
form_data = {'name' : 'CP Code Demo', 'configfilename' : '1-DR4E2_kona-ion.aws-eu-ssl.template_pm-2', 'type' : 'json', 'script' : urlencode(post_data)}
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 862, in urlencode
"or mapping object").with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 854, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object
爲什麼在這個世界上你使用'ast.literal_eval()'這個?你究竟想在這裏實現什麼? – zwer
稍微更新了我的問題。我的最終目標是對我在問題中顯示的模板中收集的數據進行urlencode編碼。 – Ramy
你用什麼庫發送'form_data'?通常你不想做自己的轉義/編碼。 – zwer