how to convert string to json in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert string to json in golang, use the json.Unmarshal() method it will convert your string to JSON and return the converted JSON object.


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 string to JSON in golang, as above mentioned I’m going to use the json.Unmarshal() method.

To use the json.Unmarshal() method, we have first import "encoding/json" package which is built in provided by golang, then we have to pass our string as a byte array with an assignable variable.

Let’s start our Golang convert string to JSON example

main.go

package main

import (
    "encoding/json"
    "fmt"
)

type Message struct {
    Name    string
    Version int64
}

func main() {

    s := `{"name":"Android", "version":13, "code":1}`
    var m Message

    err := json.Unmarshal([]byte(s), &m)
    if err != nil {
        // panic
    }

    fmt.Println(s)
}

In the above example

  1. we have import "encoding/json" package to use json.Unmarshal() method.
  2. Created JSON ( struct ) type type Message struct to use at the time of json.Unmarshal().
  3. Created sample json string which we will convert in json.
  4. Used json.Unmarshal() method and pased byte string and message struct.

That’s how we have converted a string to JSON and printed it in the console. let’s check the output.

Output

{"name":"Android", "version":13, "code":1}

Try it Yourself

I hope it helps you, All the best 👍.

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