英文:
How to convert json to string in golang and echo framework?
问题
我有一个通过POST方法接收到的JSON数据:
{"endpoint": "assistance"}
我接收到的数据如下:
json_map := make(map[string]interface{})
现在我需要将它作为字符串赋值给一个变量,但我不知道该如何做。
endpoint := c.String(json_map["endpoint"])
英文:
I have a json that I receive by post
{"endpoint": "assistance"}
I receive this like this
json_map: = make (map[string]interface{})
Now I need to assign it to a variable as a string but I don't know how to do it.
endpoint: = c.String (json_map ["endpoint"])
答案1
得分: 2
一种类型安全的方法是创建一个表示请求对象的结构体,并对其进行解组。
这样可以在出现意外请求时引发 panic。
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Endpoint string
}
func main() {
jsonBody := []byte(`{"endpoint": "assistance"}`)
data := response{}
if err := json.Unmarshal(jsonBody, &data); err != nil {
panic(err)
}
fmt.Println(data.Endpoint)
}
// assistance
这个示例程序安全地将 JSON 解码为结构体,并打印出该值。
英文:
A type safe way to do this would be creating a struct that represents your request object and unmarshalling it.
This gives you a panic on unexpected requests.
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Endpoint string
}
func main() {
jsonBody := []byte(`{"endpoint": "assistance"}`)
data := response{}
if err := json.Unmarshal(jsonBody, &data); err != nil {
panic(err)
}
fmt.Println(data.Endpoint)
}
// assistance
This program as an example safely decodes the JSON into a struct and prints the value.
答案2
得分: 0
你想要实现的不是将 JSON 转换为字符串,而是将空接口 interface{}
转换为字符串。你可以通过进行 类型断言 来实现:
endpoint, ok := json_map["endpoint"].(string)
if !ok {
// 处理底层类型不是字符串的错误
}
另外,正如 @Lex 提到的,更安全的做法可能是使用 Go 结构体来定义你的 JSON 数据。这样,所有字段都将有类型,并且你将不再需要进行这种类型断言。
英文:
What you are trying to achieve is not to convert a JSON to a string but an empty interface interface{}
to a string
You can achieve this by doing a type assertion:
endpoint, ok := json_map["endpoint"].(string)
if !ok {
// handle the error if the underlying type was not a string
}
Also as @Lex mentionned, it would probably be much safer to have a Go struct defining your JSON data. This way all your fields will be typed and you will no longer need this kind of type assertion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论