zclconf / go-cty

A type system for dynamic values in Go applications
MIT License
338 stars 70 forks source link

Nested go struct to cty value fails #150

Closed halradaideh closed 1 year ago

halradaideh commented 1 year ago

I am trying to convert go struct (which is composed of other structs) into a city value and It fails

json data i am sending

{
      "hostname": "x",
      "target_node": "x",
      "is_dc": true,
      "specs": {
        "cpu": 4,
        "memory": 9216
      },
      "source": "x",
      "disk": [
        {
          "boot_disk_pool": "x",
          "boot_disk_size": "x",
          "mount": "x"
        }
      ]
}
type Specs struct {
    Cpu    int `json:"cpu" cty:"cpu"`
    Memory int `json:"memory" cty:"memory"`
}

type VM struct {
    Hostname   string `json:"hostname" cty:"hostname"`
    TargetNode string `json:"target_node" cty:"target_node"`
    IsDc       bool   `json:"is_dc" cty:"is_dc"`
    Specs      Specs  `json:"specs" cty:"specs"`
}

func GetType() cty.Type {
    return cty.List(cty.Object(
        map[string]cty.Type{
            "hostname":    cty.String,
            "target_node": cty.String,
            "is_dc":       cty.Bool,
            "specs": cty.Map(cty.Object(
                map[string]cty.Type{
                    "cpu":    cty.Number,
                    "memory": cty.Number,
                },
            )),
        },
    ))
}

var x []VM
_ = json.Unmarshal(JSON, &x)

result, err := gocty.ToCtyValue(x, Type)
if err != nil {
    panic(err)
}

error i am getting

can't convert Go struct to cty.Map(cty.Object(map[string]cty.Type{"cpu":cty.Number, "memory":cty.Number}))

can you please provide an example, plus the list of maps too if it is possible PS: new to golang

halradaideh commented 1 year ago

removing this solved the issue cty.Map

more detailed documentation would be appreciated