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

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

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.

Related Posts