How to Convert String to JSON in Golang

To convert a string to json in Golang, you can “use the json.Unmarshal() or json.Marshal() function with the string() function.”

Method 1: Using the json.Unmarshal() function

The easiest way to convert a string to json in Go is to use the “json.Unmarshal()” function.

Here is the step-by-step guide.

  1. Import the “encoding/json” package.
  2. Create a struct to represent the JSON data.
  3. Create a variable to store the JSON string.
  4. Use the “json.Unmarshal()” function to unmarshal the JSON string into the struct.

Example

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
}

func main() {
  // Create a Person struct.
  person := Person{}

  // Create a variable to store the JSON string.
  jsonString := `{"name":"Krunal Lathiya","age":30}`

  err := json.Unmarshal([]byte(jsonString), &person)
  if err != nil {
    fmt.Println(err)
    return
  }

  fmt.Println(person)
}

Output

{"name":"Krunal Lathiya","age":30}

Method 2: Using the json.Marshal() with string()

Another way to convert a string to json is to use the “json.Marshal()” function along with the “string()” function.

Here is the step-by-step guide.

  1. Import the “encoding/json” package.
  2. Create a struct to represent the JSON data.
  3. Marshal the struct to JSON.
  4. Convert the JSON to a string.

Example

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
}

func main() {
  // Create a Person struct.
  person := Person{
    Name: "Krunal Lathiya",
    Age: 30,
  }

  // Marshal the Person struct to JSON.
  json, err := json.Marshal(person)
  if err != nil {
    fmt.Println(err)
    return
  }

  jsonString := string(json)

  fmt.Println(jsonString)
}

Output

{"name":"Krunal Lathiya","age":30}

That’s it.

Leave a Comment