dongshao4207 2017-11-15 15:11
浏览 91

如何在golang中解析json内部的切片? [关闭]

I am trying to unmarshal json data. The slice inside is deliberately without quotes, because this is what I am getting from https (added manually \ before ")

data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"

into Message struct:

type Message struct {
    QueryEndTime string `json:"queryEndTime"`
    Message []string `json:"message"`

}

but I am getting correct QueryEndTime and empty Message. I tried to change Message type but it always stays empty

var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s
Message: %s
", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []

See it in go playground https://play.golang.org/p/on0_cSKb0c.

  • 写回答

1条回答 默认 最新

  • duanhuang1967 2017-11-15 16:17
    关注
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Message struct {
        QueryEndTime string `json:"queryEndTime"`
    
        // you need to use a struct can use anon struct
        Message      []struct {
            SpamScore  int `json:"spamScore"`
            PhishScore int `json:"phishScore"`
        } `json:"message"`
    
    }
    
    func main() {
        var message Message
    
        // You can use backticks to for your example JSON, so that you don't have to escape anything.
        data := `{
            "queryEndTime" : "2017-11-15T14:39:00Z", 
            "message" : [
                {"spamScore":67, "phishScore":0}
            ]
        }`
    
        // please check for errors
        err := json.Unmarshal([]byte(data), &message)
        if err != nil {
            fmt.Println(err)
        }
    
        // +v prints structs very nicely 
        fmt.Printf("%+v
    ", message)
    }
    

    https://play.golang.org/p/Mu3WZCej3L

    Have fun!

    评论

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录