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().


Related Tutorials

Golang JSON to string

Golang JSON to XML

Golang JSON to Map

Golang JSON to Struct


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 👍.

Try it Yourself

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts