Home > Enterprise >  Define structure in golang
Define structure in golang

Time:04-15

I am working on a project in which I receive payload data in the following format:

"name":"John",
"date":"2022-04-14",
"price":200,
"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]

How should I define the struct for this? If you know please let me know. Thanks!

CodePudding user response:

This part

"dependencies":[
{
"element_1":{
"items":[2,4],
"pricing":[1,2]
}
},
{
"element_2":{
"items":[5,4],
"pricing":[1,6]
}
}
]

Looks like


type XXX struct {
  Dependencies []map[string]Dependency `json:"dependencies"`
}

type Dependency struct {
Items []int // json…
Pricing []int // json…
}

But I am not sure… if element_x is dynamic or not. If it is predefined, ok.

CodePudding user response:

If your json is

{
    "name": "John",
    "date": "2022-04-14",
    "price": 200,
    "dependencies":
    [
        {
            "element_1":
            {
                "items":
                [
                    2,
                    4
                ],
                "pricing":
                [
                    1,
                    2
                ]
            }
        },
        {
            "element_2":
            {
                "items":
                [
                    5,
                    4
                ],
                "pricing":
                [
                    1,
                    6
                ]
            }
        }
    ]
}

Then you can create struct like this

type DemoStruct struct {
    Name         string       `json:"name"`        
    Date         string       `json:"date"`        
    Price        int64        `json:"price"`       
    Dependencies []Dependency `json:"dependencies"`
}

type Dependency struct {
    Element1 *Element `json:"element_1,omitempty"`
    Element2 *Element `json:"element_2,omitempty"`
}

type Element struct {
    Items   []int64 `json:"items"`  
    Pricing []int64 `json:"pricing"`
}
  •  Tags:  
  • go
  • Related