0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golangで配列(struct)をjsonへ変換する

Posted at

jsonパッケージを使う

import "encoding/json"

変換する

jsonパッケージの引数に配列を指定してあげれば変換してくれる


data, _ := json.Marshal(m)

例えばKubernetesのPod一覧をjsonに変換するもの

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() {
    // Kubeconfigのファイルパスを指定
    kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube", "config")
    config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
    if err != nil {
        log.Fatal(err)
    }

    // Kubeconfigを読み込む
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatal(err)
    }

    // Pod一覧を呼び出す
    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))
}

実行結果


{
	"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"
}

marshalとunmarshal

marshalは元帥?という意味?黒ひげ?

marshal

  • structをjsonに変換するときに使う

unmarshal

  • ネットワーク越しに受け取ったjsonのbyte配列をjsonへ変換するときに使う
    • たぶんレスポンスヘッダーとかそのあたりをうまいこと取り除いてくれるんだと思う
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?