So I am receiving this {"text":"hello, world!"}
on my endpoint and I am writing in Go.
How can I access it as such?
query = hello, world!
CodePudding user response:
This data is a JSON, so you can unmarshal it to a corresponding struct.
package main
import (
"encoding/json"
"fmt"
"log"
)
type MyData struct {
Text string `json:"text"`
}
func main() {
data := `{"text":"hello, world!"}`
var myData MyData
err := json.Unmarshal([]byte(data), &myData)
if err != nil {
log.Fatal(err)
}
fmt.Println(myData.Text)
//Alternative way using a map of interface{}
m := make(map[string]interface{})
err = json.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatal(err)
}
fmt.Println(m["text"])
}