In kubernetes python client, curl command returns the output in str and I am expecting output in json format

1/15/2019

I am creating a program in kubernetes python client, and which curls an url inside the pod and expect the output in json, instead the output comes in form of str. Following is my program:

from kubernetes import client, config, watch
from kubernetes.stream import stream
config.load_kube_config()
k8s_corev1 = client.CoreV1Api()

def run_command_inside_pod(api_instance, pod, ns, exec_command):
    api_response = stream(api_instance.connect_get_namespaced_pod_exec, pod, ns,
                          command=exec_command,
                          stderr=True, stdin=False,
                          stdout=True, tty=False)
    return api_response


def metrics_datastore_check():
    """

    :param name:
    :return:
    """
    name = "metrics-datastore-0"

    print("Waiting for pod %s to get ready." % name)
    exec_command = ['curl', '--silent', '-i', 'localhost:9200/_cluster/health?pretty']
    es_status = run_command_inside_pod(k8s_corev1,name,"default",exec_command)
    print (es_status)

    print (type(es_status))

metrics_datastore_check()

The above program returns the following output:

(env) [root@ip-10-0-1-48 k8s_Client]# python2 es_pod.py 
Waiting for pod metrics-datastore-0 to get ready.
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 470

{
  "cluster_name" : "metrics-datastore",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 2,
  "number_of_data_nodes" : 1,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0
}

<type 'str'>

As you can clearly see the type of return value is str and hence I am unable to parse it properly using json tools. Could anyone please help me either to get that output in form of dict or converting that str to dict.

-- Prafull Ladha
json
kubernetes
kubernetes-python-client
python

1 Answer

1/15/2019

json.loads() -> This parses a string object and returns json object

import json
json_object = json.loads(es_status)
print(json_object['status'])
-- sanster_23
Source: StackOverflow