How to Convert Golang String to JSON

A Golang string is a set of all strings that contain 8-bit bytes. The json encoding is possible in Go using the package “encoding/json”.

Golang String to JSON

To convert a string to json in Golang, use the json.Marshal() function.

The json.Marshal() is a json package function in Go that encodes objects in JSON format known as marshaling. Use the Marshal() function to convert objects to JSON.

package main

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

func main() {
  str := "here is the data"
  jsondata, err := json.Marshal(str)
  if err != nil {
    log.Println(err)
  }
  fmt.Println(string(jsondata), reflect.TypeOf(jsondata))
}

Output

"here is the data" []uint8

In this example, we imported the four built-in packages.

  1. encoding/json
  2. fmt
  3. log
  4. reflect

The encoding/json package provides all the functions related to json conversion.

The fmt package provides all the functions related to formatting strings or integers and printing them.

The log package provides a type Logger with methods for formatting output.

The reflect package implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The effect package provides a method called TypeOf() that will help you find the data type of a variable.

Inside the main() function, we defined a string that we will convert into json string.

The json.Marshal() function converts a simple string to json string. It returns the output and err if it throws one.

The fmt.Println() function formats using the default formats for its operands and writes to standard output.

The output is a json string as you can see.

That’s it for this tutorial.

Related posts

Golang string to byte array

Golang int to string

Leave a Comment