Babr
Babr

Reputation: 2081

How to create a json object out of structs

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.

Upvotes: 2

Views: 340

Answers (3)

CallMeLoki
CallMeLoki

Reputation: 1361

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

no need to change : to , too

also notice that the error is compile time error not runtime

here is a tool I use when my json is too big and i want struct out of it

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

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

Upvotes: 2

user9815655
user9815655

Reputation:

To put the quotation for all field The below code

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

as follows

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

I hope this is help for u

Upvotes: 0

Related Questions