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.
- Import the “encoding/json” package.
- Create a struct to represent the JSON data.
- Create a variable to store the JSON string.
- 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.
- Import the “encoding/json” package.
- Create a struct to represent the JSON data.
- Marshal the struct to JSON.
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.