Golang 相当于 Python json.dumps 和 json.loads
Golang equivalent to Python json.dumps and json.loads
这是一个非常奇怪的情况,但我需要将字符串化的 json 转换为我可以解组的有效内容:
"{\"hello\": \"hi\"}"
我希望能够将其解组为这样的结构:
type mystruct struct {
Hello string `json:"hello,string"`
}
我知道解组通常需要字节,但我正在尝试将我当前获得的内容转换为结构化的内容。
有什么建议吗?
问题是 encoding/json
包接受格式正确的 JSON,在这种情况下,您拥有的初始 JSON 已经转义引号,首先您必须取消转义它们,一种方法是使用 the strconv.Unquote
function,这是一个示例片段:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type mystruct struct {
Hello string `json:"hello,omitempty"`
}
func main() {
var rawJSON []byte = []byte(`"{\"hello\": \"hi\"}"`)
s, _ := strconv.Unquote(string(rawJSON))
var val mystruct
if err := json.Unmarshal([]byte(s), &val); err != nil {
// handle error
}
fmt.Println(s)
fmt.Println(err)
fmt.Println(val.Hello)
}
这是一个非常奇怪的情况,但我需要将字符串化的 json 转换为我可以解组的有效内容:
"{\"hello\": \"hi\"}"
我希望能够将其解组为这样的结构:
type mystruct struct {
Hello string `json:"hello,string"`
}
我知道解组通常需要字节,但我正在尝试将我当前获得的内容转换为结构化的内容。 有什么建议吗?
问题是 encoding/json
包接受格式正确的 JSON,在这种情况下,您拥有的初始 JSON 已经转义引号,首先您必须取消转义它们,一种方法是使用 the strconv.Unquote
function,这是一个示例片段:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type mystruct struct {
Hello string `json:"hello,omitempty"`
}
func main() {
var rawJSON []byte = []byte(`"{\"hello\": \"hi\"}"`)
s, _ := strconv.Unquote(string(rawJSON))
var val mystruct
if err := json.Unmarshal([]byte(s), &val); err != nil {
// handle error
}
fmt.Println(s)
fmt.Println(err)
fmt.Println(val.Hello)
}