Golang将JSON映射为结构

I have a JSON which I need to extract the data out of it using a struct:

I am trying to map it to the below 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"`
}

This is my json:

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

My questions are:

  1. How to structure my struct?
  2. How to read the name, values and comments?

So far I couldn't read the data using the below code:

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

the getJson function:

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)
}

Your struct is correct. All you need is love to use json.Unmarshal function with a correct target object which is slice of Message instances: []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)
}

Your JSON seems to be an array. Just unmarshall it to a slice. Something like:

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

Should work.

I don't know if this will be any help now, but i've recently written utility for generating exact go type from json input: https://github.com/m-zajac/json2go

For json from first post it generates this struct:

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

You can decode data to this struct like this:

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