将JSON成员字符串转换为JSON对象

死队

我有这个结构:

type ResponseStatus struct {
    StatusCode int
    Message    string
    Data       string `json:"data"`
}

type Pets struct {
    Id   int    `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
    Type string `json:"type"`
}

这是我的json结果:

{
    "StatusCode": 200,
    "Message": "Hello framework - OK",
    "data": "[{\"id\":1,\"name\":\"george\",\"age\":2,\"type\":\"dog\"},{\"id\":2,\"name\":\"walter\",\"age\":1,\"type\":\"rabbit\"},{\"id\":3,\"name\":\"tom\",\"age\":1,\"type\":\"cat\"},{\"id\":4,\"name\":\"doggo\",\"age\":5,\"type\":\"dog\"},{\"id\":5,\"name\":\"torto\",\"age\":3,\"type\":\"turtle\"},{\"id\":6,\"name\":\"jerry\",\"age\":1,\"type\":\"hamster\"},{\"id\":7,\"name\":\"garf\",\"age\":2,\"type\":\"cat\"},{\"id\":8,\"name\":\"milo\",\"age\":4,\"type\":\"dog\"},{\"id\":9,\"name\":\"kimi\",\"age\":2,\"type\":\"cat\"},{\"id\":10,\"name\":\"buck\",\"age\":1,\"type\":\"rabbit\"}]"
}

我该如何在结果数据中使用JSON转义双引号,如下所示:

{
  "StatusCode": 200,
  "Message": "Hello framework - OK",
  "data": [
    {"id": 1,"name": "george","age": 2,"type": "dog"},
    {"id": 2,"name": "walter","age": 1,"type": "rabbit"},
    {"id": 3,"name": "tom","age": 1,"type": "cat"},
    {"id": 4,"name": "doggo","age": 5,"type": "dog"},
    {"id": 5,"name": "torto","age": 3,"type": "turtle"},
    {"id": 6,"name": "jerry","age": 1,"type": "hamster"},
    {"id": 7,"name": "garf","age": 2,"type": "cat"},
    {"id": 8,"name": "milo","age": 4,"type": "dog"},
    {"id": 9,"name": "kimi","age": 2,"type": "cat"},
    {"id": 10,"name": "buck","age": 1,"type": "rabbit"}
  ]
}
Bert Verhees:

您做得很好,仅需注意以下几点:删除方括号前后的引号,并应使数据类型为[] Pets(我将其称为Pet的结构,因为每个项目都包含一个Pet)。方括号是JSON构造的一部分。然后,您无需转义引号,因为它们成为JSON标识符。

用您的方式,它变成一个长字符串,很明显,这不是您想要的。

这些是适合您第二个JSON的结构

type ResponseStatus struct {
   StatusCode int    
   Message    string 
   Data       []Pet  `json:"data"`
}

type Pet struct {
   Id   int    `json:"id"`
   Name string `json:"name"`
   Age  int    `json:"age"`
   Type string `json:"type"`
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章