douxiza9868 2017-02-09 12:28
浏览 74
已采纳

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)
}
  • 写回答

3条回答 默认 最新

  • doujimiao7480 2017-02-09 13:40
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c