import "encoding/json"
If you specify an array as an argument of json package, it will be converted
data, _ := json.Marshal(m)
package main
import (
"context"
"encoding/json"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"path/filepath"
)
func main() {
//Specify the file path of Kubeconfig
kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
//Load Kubeconfig
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
//Call the pod list
namespace := "default"
pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
log.Fatalln("failed to get pods:", err)
}
m := map[string]string{}
// print pods
// pods.Items: []v1.Pod
for _, pod := range pods.Items {
m[pod.Name] = string(pod.Status.Phase)
}
data, _ := json.Marshal(m)
fmt.Printf(string(data))
}
Execution result
{
"external-dns-547f4784f7-852zf": "Running",
"nginx-deployment-574b87c764-8vwdz": "Running",
"nginx-deployment-574b87c764-dnr6m": "Running",
"v01-app-54fc4b5d44-k5zfp": "Running",
"v01-db-5b756dc6b-57grv": "Running"
}
Is marshal a marshal? means? Blackbeard?
marshal --Used when converting struct to json
unmarshal --Used when converting the json byte array received over the network to json ――I think it will remove the response header and its surroundings nicely.
Recommended Posts