如何在Golang中拆分和分隔这个字符串?

huangapple go评论59阅读模式
英文:

How to split and delimit this string in Golang?

问题

你好,我现在将为你提供翻译服务。以下是你要翻译的内容:

所以我在我的端点上收到了这个 {"text":"hello, world!"},我正在使用Go语言编写代码。

我该如何访问它?

query = hello, world!

英文:

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!

答案1

得分: 2

这个数据是一个JSON,所以你可以将其解组为相应的结构体。

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)

    // 使用一个接口类型的映射作为替代方法
    m := make(map[string]interface{})
    err = json.Unmarshal([]byte(data), &m)
    if err != nil {
      log.Fatal(err)
    }
    fmt.Println(m["text"])
   
}

希望对你有帮助!

英文:

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

huangapple
  • 本文由 发表于 2022年3月2日 04:02:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/71314047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定