dongzhizhai4070 2018-06-06 07:22 采纳率: 0%
浏览 96
已采纳

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

I have this struct:

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"`
}

and this is my json result:

{
    "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\"}]"
}

How can I escaped double quotes in my result data as JSON like this:

{
  "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"}
  ]
}
  • 写回答

1条回答 默认 最新

  • duan1989643 2018-06-06 07:37
    关注

    You are doing fine, just a few remarks: Remove the quote before and after the square brackets, and you should make Data of type []Pets (which struct I would call Pet, because every item contains a single Pet). The square-brackets are part of the JSON construct. And then you don't need to escape the quotes, because they become JSON identifiers.

    In your way, it becomes a single long string, which, clearly, is not what you intent to have.

    These are the structures that fit on your second 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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功