duanmi4379 2018-07-07 07:56
浏览 56
已采纳

如何使用结构创建json对象

I'm very new to golang and I'd like to make a json object like this:

{
    "name" : "animals",
    "children" : [
        {"name":"dog", "value": 5},
        {"name":"cat", "value": 4},
        {"name":"fish", "value": 10}
    ]
}   

The code that I came up with:

type Child struct {
        Name string
        Value int
    }

type DataMap struct {
        Name string
        Children []Child
    }    
m := DataMap{"animals", [{"cat": 5 }, {"dog": 4}, {"fish":10}] }  
cj, _ := json.Marshal(m)

But I get error:

   syntax error: unexpected {, expecting expression

Ideally, I'd like to append the Children slice to the DataMap in a loop but I don't know how to do so. Appreciate your hints.

  • 写回答

3条回答 默认 最新

  • dstjh46606 2018-07-07 08:08
    关注

    You have misunderstand the struct initialization syntax(as many new incomers), here is an example:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Child struct {
            Name string
            Value int
        }
    
    type DataMap struct {
            Name string
            Children []Child
        }    
    
    func main() {
        m := DataMap{"animals", []Child{{"cat", 5}, {"dog", 10 } } }  
        cj, _ := json.Marshal(m)
    
        fmt.Printf("%s", cj)
    }
    

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

    In a loop:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Child struct {
            Name string
            Value int
        }
    
    type DataMap struct {
            Name string
            Children []Child
        }    
    
    func main() {
        m := DataMap{"animals", []Child{}}
        for _, item := range []Child{{"cat", 5}, {"dog", 10 }} {
           m.Children = append(m.Children, item)
        }
        cj, _ := json.Marshal(m)
    
        fmt.Printf("%s", cj)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块