我在将通过脚本构建的字符串转换为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
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
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>
这里是产生上述代码:
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
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
2017-07-25
Ramy
+0
为什么在这个世界上你使用'ast.literal_eval()'这个?你究竟想在这里实现什么? –
+0
稍微更新了我的问题。我的最终目标是对我在问题中显示的模板中收集的数据进行urlencode编码。 –
+0
你用什么库发送'form_data'?通常你不想做自己的转义/编码。 –