How to Serialize JSON String in Go

To serialize json string in Go, you can “use the json.Marshal()” function to a slice of bytes. You can deserialize a slice of bytes into a Golang value using the “json.Unmarshal()” function.

Syntax

func Marshal(v interface{}) ([]byte, error)

If Marshal() fails to serialize the input value, it will return a non-nil error.

Few things you need to keep in mind:

  1. Map keys must be strings.
  2. Map values must be types serializable by the json package.
  3. The following types are not supported: Channel, complex, and function.
  4. Cyclic data structures are not supported.
  5. Pointers will be encoded (and later decoded) as the values they point to (or ‘null’ if the pointer is nil).

Example 1: Serializing JSON String in Go

package main

import (
  "encoding/json"
  "fmt"
  "log"
)

 // Define a struct to represent a person
type Student struct {
  Name string `json:"name"`
  Age int `json:"age"`
}

func main() {
  // Create an instance of the Student struct
  student := Student{Name: "Krunal", Age: 30}

  // Serialize the student struct to JSON
  jsonBytes, err := json.Marshal(student)
  if err != nil {
    log.Fatalf("Error marshaling JSON: %v", err)
  }

  // Convert the JSON bytes to a string and print it
  jsonString := string(jsonBytes)
  fmt.Println("JSON string:", jsonString)
}

Output

JSON string: {"name":"Krunal","age":30}

Example 2: Skipping escaping

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  FirstName string `json:"firstName"`
  LastName string `json:"lastName"`
}

func main() {
  in := `{"firstName":"Krunal","lastName":"Lathiya"}`

  rawIn := json.RawMessage(in)
  bytes, err := rawIn.MarshalJSON()
  if err != nil {
    panic(err)
  }

  var p Person
  err = json.Unmarshal(bytes, &p)
  if err != nil {
    panic(err)
  }

  fmt.Printf("%+v \n", p)
}

Output

{FirstName:John LastName:Dow}

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.