Convert array (struct) to json with golang

use json package

import "encoding/json"

Convert

If you specify an array as an argument of json package, it will be converted


data, _ := json.Marshal(m)

For example, converting a Kubernetes pod list to 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() {
    //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"
}

marshal and unmarshal

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

Convert array (struct) to json with golang
Convert Excel data to JSON with python
Convert 202003 to 2020-03 with pandas
Convert dict to array
Convert json to excel
How to convert JSON file to CSV file with Python Pandas
Convert Select query obtained from Postgre with Go to JSON
Convert Tweepy Status object to JSON
Convert .ipynb to .html (with BatchFile)
Convert list to DataFrame with python
Convert PDF to image with ImageMagick
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Convert memo at once with Python 2to3
Convert from PDF to CSV with pdfplumber
Convert character strings to features with RoBERTa
Convert Hiragana to Romaji with Python (Beta)
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Sample to convert image to Wavelet with Python
Convert DICOM to PNG with Ascending and Descending
Convert data with shape (number of data, 1) to (number of data,) with numpy.
Convert PDF to image (JPEG / PNG) with Python
Convert to HSV
Just add the python array to the json data
Convert PDFs to images in bulk with Python
Convert mp4 to mp3 with ffmpeg (thumbnail embedded version)
Add rows to an empty array with numpy
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
Easily convert Jupyter Notebooks to blogs with fastpages
How to read an array with Python's ConfigParser
Convert a multidimensional list (array) to one dimension
Convert json format data to txt (using yolo)
How to convert (32,32,3) to 4D tensor (1,32,32,1) with ndarray type
Convert strings to character-by-character list format with python
I want to convert an image to WebP with lollipop
Resize multipart.File type image with golang ~ Upload to S3
I convert AWS JSON data to CSV like this
0 Convert unfilled date to datetime type with regular expression
Convert a text file with hexadecimal values to a binary file
How to convert horizontally held data to vertically held data with pandas
How to convert a class object to a dictionary with SQLAlchemy
Convert the image in .zip to PDF with Python
Try to get the contents of Word with Golang
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
Convert / return class object to JSON format in Python
How to convert Json file to CSV format or EXCEL format
Convert numeric variables to categorical with thresholds in pandas
Convert Pascal VOC format xml file to COCO format json file
Convert elements of numpy array from float to int
[Python] Use JSON with Python
Getting Started with Golang 2
Convert kanji to kana
Convert jupyter to py
Getting Started with Golang 1
Merge array with PyYAML
Convert keras-yolo3 to onnx
How to read JSON
Getting Started with Golang 3
Call bash with golang
Getting Started with Golang 4