how to convert json to string in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert json to string in golang, use json.Marshal() with string() method, it will convert json to string. You have to only pass your json in json.Marshal().


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows


Today, I will show you how do I convert a json to string in golang, as above mentioned I’m going to use json.Marshal() with string() method.

Let’s start our Golang convert json to string example

main.go

package main

import (
	"encoding/json"
	"fmt"
)

type Iot struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

func main() {
	iot := Iot{
		Id:   1,
		Name: "infinitbility",
	}

	// Context is []byte, so you can keep it as string in DB
	fmt.Println("ctx:", iot)

	// Marshal back to json (as original)
	out, _ := json.Marshal(&iot)
	fmt.Println(string(out))
}

In the above example, we have converted the json value to a string and printed in golang console. let’s check the output.

Output

ctx: {1 infinitbility}
{"id":1,"name":"infinitbility"}

I hope it helps you, All the best 👍.

Follow me on Twitter