Skip to main content
added 103 characters in body
Source Link
Cerise Limón
  • 118.8k
  • 13
  • 271
  • 259

Use json.RawMessage to get the raw JSON text of the inputs field:

type Item struct {
    Type   string `json:"type"`
    Inputs json.RawMessage
}

Use it like this:

var data Configuration
if err := json.Unmarshal([]byte(myJson), &data); err != nil {
    // handle error
}

// Loop over items and unmarshal items.Inputs to Go type specific
// to each input type.    
for _, item := range data.Items {
    switch item.Type {
    case "type-of-item":
        var v struct{ Input1 string }
        if err := json.Unmarshal(item.Inputs, &v); err != nil {
            // handle error
        }
        fmt.Printf("%s has value %+v\n", item.Type, v)

    }
}

Run it on the playground.

Use json.RawMessage to get the raw JSON text of the inputs field:

type Item struct {
    Type   string `json:"type"`
    Inputs json.RawMessage
}

Use it like this:

var data Configuration
if err := json.Unmarshal([]byte(myJson), &data); err != nil {
    // handle error
}

for _, item := range data.Items {
    switch item.Type {
    case "type-of-item":
        var v struct{ Input1 string }
        if err := json.Unmarshal(item.Inputs, &v); err != nil {
            // handle error
        }
        fmt.Printf("%s has value %+v\n", item.Type, v)

    }
}

Run it on the playground.

Use json.RawMessage to get the raw JSON text of the inputs field:

type Item struct {
    Type   string `json:"type"`
    Inputs json.RawMessage
}

Use it like this:

var data Configuration
if err := json.Unmarshal([]byte(myJson), &data); err != nil {
    // handle error
}

// Loop over items and unmarshal items.Inputs to Go type specific
// to each input type.    
for _, item := range data.Items {
    switch item.Type {
    case "type-of-item":
        var v struct{ Input1 string }
        if err := json.Unmarshal(item.Inputs, &v); err != nil {
            // handle error
        }
        fmt.Printf("%s has value %+v\n", item.Type, v)

    }
}

Run it on the playground.

Source Link
Cerise Limón
  • 118.8k
  • 13
  • 271
  • 259

Use json.RawMessage to get the raw JSON text of the inputs field:

type Item struct {
    Type   string `json:"type"`
    Inputs json.RawMessage
}

Use it like this:

var data Configuration
if err := json.Unmarshal([]byte(myJson), &data); err != nil {
    // handle error
}

for _, item := range data.Items {
    switch item.Type {
    case "type-of-item":
        var v struct{ Input1 string }
        if err := json.Unmarshal(item.Inputs, &v); err != nil {
            // handle error
        }
        fmt.Printf("%s has value %+v\n", item.Type, v)

    }
}

Run it on the playground.