猿问

解析戈朗中的转义 json 字符串

假设我有这个 json 字符串:

{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}

我想将上面的字符串转换为结构:

{
  A string
  B string
  C string
  D int
  E string
  }

我不知道该怎么做,因为我已经做了引用和取消引用,但似乎还没有成功。


MM们
浏览 136回答 3
3回答

当年话下

在像这样取消引号之前,请包装传入的字符串:s,err := strconv.Unquote(`"`+yourstring+`"`)然后,您可以继续取消编组。

梦里花落0921

有点黑客,但输入字符串是如果它在JSON对象中将被编码的方式,所以你可以这样做:x:=json.RawMessage(`"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"`)var v stringerr:=json.Unmarshal(x,&v)var x MyStructjson.Unmarshal([]byte(v),&x)  

红颜莎娜

你可以使用mfathirirhas建议的方法,我已经创建了一个小代码来描述你的场景,如下所示:Unquotestrconvpackage mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strconv")type response struct {&nbsp; &nbsp; A string&nbsp; &nbsp; B string&nbsp; &nbsp; C string&nbsp; &nbsp; D int&nbsp; &nbsp; E string}func main() {&nbsp; &nbsp; str := (`"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"`)&nbsp; &nbsp; fmt.Printf(str)&nbsp; &nbsp; s, err := strconv.Unquote(str)&nbsp; &nbsp; fmt.Println()&nbsp; &nbsp; fmt.Println(s, err)&nbsp; &nbsp; var resp response&nbsp; &nbsp; if err := json.Unmarshal([]byte(s), &resp); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(resp)}输出:"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"{"A":"a","B":"b","C":"c","D":2,"E":"e"} <nil>{a b c 2 e}
随时随地看视频慕课网APP

相关分类

Go
我要回答