How to Convert JSON String to Go String

You can use the json.Unmarshal() function to convert a JSON string to a Go string. The json.Unmarshal() function from the encoding/json package decodes JSON-encoded data into a Go data structure.

Assuming you have a JSON string representing a simple string value, you can use the json.Unmarshal() function to decode it into a Go string variable.

package main

import (
  "encoding/json"
  "fmt"
)

func main() {
  jsonString := `"We are the world"`
  var goString string

  err := json.Unmarshal([]byte(jsonString), &goString)
  if err != nil {
    fmt.Println("Error decoding JSON:", err)
    return
  }

  fmt.Println("JSON string:", jsonString)
  fmt.Println("Go string:", goString)
}

Output

JSON string: "We are the world"
Go string: We are the world

In this example, we first define a JSON string representing the value “We are the world”.

We also defined a variable goString of type string which will carry the decoded value.

Next, we use the json.Unmarshal() function to decode the JSON string into the goString variable.

The first argument to json.Unmarshal() function is the JSON data as a byte slice.

The second argument is a pointer to the variable holding the decoded value.

If the decoding is successful, the value of goString will be “We are the world”.

If there’s an error, the err variable will contain information about the error.

Finally, we print the original JSON string and the decoded Go string to the console.

Conclusion

To convert a JSON string to a Golang string, use the “encoding/json” package’s json.Unmarshal() function.

Further reading

How to Convert Golang String to JSON

Pretty Print JSON in Golang

Leave a Comment