我正在通过Kubernetes API代理动词从pod的Web服务器请求一些JSON数据。那就是:
corev1 = kubernetes.client.CoreV1Api()
res = corev1.connect_get_namespaced_pod_proxy_with_path(
'mypod:5000', 'default', path='somepath', path2='somepath')
print(type(res))
print(res)
调用成功,并返回一个str
,其中包含来自pod的Web服务的序列化JSON数据。不幸的是,res
现在看起来像这样……根本不是有效的JSON,因此json.loads(res)
拒绝对其进行解析:
{'x': [{'xx': 'xxx', ...
如您所见,字符串化的响应看起来像Python字典,而不是有效的JSON。关于如何安全地转换回正确的JSON或正确的Python dict
的任何建议?
答案 0 :(得分:1)
在阅读了Kubernetes Python客户端的一些代码之后,现在很清楚connect_get_namespaced_pod_proxy()
和connect_get_namespaced_pod_proxy_with_path()
通过调用将来自远程API调用的响应主体转换为str
self.api_client.call_api(..., response_type='str', ...)
(core_v1_api.py)。因此,我们受困于Kubernetes API客户端,它仅向我们提供表示原始JSON响应正文的dict()
的字符串表示形式。
要将字符串转换回dict()
,anwer to Convert a String representation of a Dictionary to a dictionary?建议使用ast.literal_eval()
。想知道这是否是明智的选择,我发现answer to Is it a best practice to use python ast library for operations like converting string to dict说这是明智的选择。
import ast
corev1 = kubernetes.client.CoreV1Api()
res = corev1.connect_get_namespaced_pod_proxy_with_path(
'mypod:5000', 'default', path='somepath', path2='somepath')
json_res = ast.literal_eval(res)
答案 1 :(得分:0)
我在Pod上执行时遇到了类似的问题,并找到了解决方案。 我想它也可能对您有用。
例如:
wsclient_obj = stream(v1.connect_get_namespaced_pod_exec, m
y_name,
'default',
command=['/bin/sh', '-c', 'echo $MY_VAR'],
stderr=True,
stdin=False,
stdout=True,
tty=False,
_preload_content=False
)
wsclient_obj.run_forever(timeout=10)
response_str = wsclient_obj.read_stdout()
之后json.loads(response_str)
将起作用:)