如何使用结构创建json对象

时间:2018-07-07 07:56:31

标签: go

我对golang还是很陌生,我想制作一个json对象,如下所示:

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

我想到的代码:

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)

但是我得到了错误:

   syntax error: unexpected {, expecting expression

理想情况下,我想在循环中将Children切片附加到DataMap,但我不知道该怎么做。 感谢您的提示。

3 个答案:

答案 0 :(得分:2)

type DataMap struct {
        Name string
        Children []map[string]int
}

也无需将:更改为,

还请注意,该错误是编译时错误而不是运行时

here是我的json太大并且我想要结构化时使用的工具

答案 1 :(得分:2)

您对结构初始化语法有误解(与许多新收入者一样),下面是一个示例:

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

循环中:

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 :(得分:0)

为所有字段添加报价 下面的代码

{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}

如下

{"name":"dog", "value": "5"},
{"name":"cat", "value": "4"},
{"name":"fish", "value": "10"}

我希望这对您有帮助