Golang地图json到struct

时间:2017-02-09 12:28:37

标签: json go struct

我有一个JSON,我需要使用struct来提取数据:

我正在尝试将其映射到以下结构:

type Message struct {
    Name   string `json:"name"`
    Values []struct {
        Value int `json:"value,omitempty"`
        Comments int `json:"comments,omitempty"`
        Likes    int `json:"likes,omitempty"`
        Shares   int `json:"shares,omitempty"`
    } `json:"values"`
}

这是我的json:

[{
        "name": "organic_impressions_unique",
        "values": [{
            "value": 8288
        }]
    }, {
        "name": "post_story_actions_by_type",
        "values": [{
            "shares": 234,
            "comments": 838,
            "likes": 8768
        }]
    }]

我的问题是:

  1. 如何构建我的结构?
  2. 如何阅读名称,数值和评论?
  3. 到目前为止,我无法使用以下代码读取数据:

    msg := []Message{}
    getJson("https://json.url", msg)
    println(msg[0])
    

    getJson函数:

    func getJson(url string, target interface{}) error {
        r, err := myClient.Get(url)
        if err != nil {
            return err
        }
        defer r.Body.Close()
    
        return json.NewDecoder(r.Body).Decode(target)
    }
    

3 个答案:

答案 0 :(得分:6)

你的结构是正确的。所有你需要的是使用json.Unmarshal函数和正确的目标对象,它是Message个实例的一部分:[]Message{}

Correct unmarshaling

type Message struct {
    Name   string `json:"name"`
    Values []struct {
        Value    int `json:"value,omitempty"`
        Comments int `json:"comments,omitempty"`
        Likes    int `json:"likes,omitempty"`
        Shares   int `json:"shares,omitempty"`
    } `json:"values"`
}

func main() {
    input := []byte(`
[{
    "name": "organic_impressions_unique",
    "values": [{
        "value": 8288
    }]
    }, {
        "name": "post_story_actions_by_type",
        "values": [{
            "shares": 234,
            "comments": 838,
            "likes": 8768
        }]
    }]
`)

    messages := []Message{} // Slice of Message instances
    json.Unmarshal(input, &messages)
    fmt.Println(messages)
}

答案 1 :(得分:3)

您的JSON似乎是一个数组。只需将其拆分为一片即可。类似的东西:

var messages []Message
err := json.Unmarshal(json, &messages)

应该工作。

答案 2 :(得分:0)

我不知道现在是否会有任何帮助,但我最近编写了用于从json输入生成精确go类型的实用程序:https://github.com/m-zajac/json2go

对于第一篇文章的json,它会生成这个结构:

type Object struct {
    Name    string  `json:"name"`
    Values  []struct {
        Comments    *int    `json:"comments,omitempty"`
        Likes       *int    `json:"likes,omitempty"`
        Shares      *int    `json:"shares,omitempty"`
        Value       *int    `json:"value,omitempty"`
    }   `json:"values"`
}

您可以将数据解码到此结构,如下所示:

var docs []Object
if err := json.Unmarshal(input, &docs); err != nil {
    // handle error
}
相关问题