How to convert string to json in Go

Created
Modified

Decoding JSON Into Structs

Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types.

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.

package main

import (
  "encoding/json"
)

type Message struct {
  Name    string
  Version int64
}

func main() {

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

  var m Message

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

}

If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Unmarshal will decode only the fields that it can find in the destination type.

Marshaling Structured Data

To encode JSON data we use the json.Marshal function.

m := Message{
  Name:    "Android",
  Version: 13,
}

// func Marshal(v interface{}) ([]byte, error)
b, _ := json.Marshal(&m)
fmt.Println(string(b))
{"Name":"Android","Version":13}

Decoding arbitrary data

Without knowing this data’s structure, we can decode it into an map[string]interface{} value with Unmarshal:

s := `{"name":"Android", "version":13}`

// var m interface{}
var m map[string]interface{}
err := json.Unmarshal([]byte(s), &m)

// s := `[{"name":"Android", "version":13}]`
// map[] json: cannot unmarshal array into Go value of type map[string]interface {}
map[name:Android version:13]

Ignoring Empty Fields

In some cases, we would want to ignore a field in our JSON output, if its value is empty. We can use the “-” property for this purpose.

type Message struct {
  Name    string
  Version int64 `json:"-"`
}

m := Message{
  Name:    "Android",
  Version: 13,
}

b, err := json.Marshal(&m)
{"Name":"Android"}

Related Tags