How to split and delimit this string in Golang?

Issue

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!

Solution

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"])
   
}

Answered By – Fenistil

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.