Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang将json映射到结构_Json_Go_Struct - Fatal编程技术网

Golang将json映射到结构

Golang将json映射到结构,json,go,struct,Json,Go,Struct,我有一个JSON,我需要使用结构从中提取数据: 我正在尝试将其映射到以下结构: type Message struct { Name string `json:"name"` Values []struct { Value int `json:"value,omitempty"` Comments int `json:"comments,omitempty"` Likes int `json:"likes,omitempt

我有一个JSON,我需要使用结构从中提取数据:

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

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
        }]
    }]
我的问题是:

  • 如何构造我的结构
  • 如何读取名称、值和注释
  • 到目前为止,我无法使用以下代码读取数据:

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

    您的JSON似乎是一个数组。把它拆成一片就行了。比如:

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

    应该可以工作。

    您的结构是正确的。您只需要将函数与正确的目标对象一起使用,该对象是
    消息
    实例的一部分:
    []消息{}

    :


    我不知道这现在是否有帮助,但我最近编写了一个实用程序,用于从json输入生成精确的go类型:

    对于来自first post的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
    }
    

    问题是什么?我需要知道如何构造我的结构,以及如何读取名称、值和注释等…@JonathonReinhart我想不清楚,我更新了问题您是否编写了任何试图使用结构定义的代码?它有用吗?它失败了吗?它报告错误了吗?我编辑了我的问题,提到解组器中的代码
    json
    代表什么?url?检查我的问题plz中的getJson函数,我现在将其添加到解组器中json代表您的问题中的json blob,您从某种程度上获取它
    var docs []Object
    if err := json.Unmarshal(input, &docs); err != nil {
        // handle error
    }