struct tagだけでは多分無理なのでjson.Marshaler interfaceを自前で実装してやる。
main.go
package main
import (
"encoding/json"
"fmt"
)
type RootStruct struct {
Values []valStruct
}
type valStruct struct {
JsonKey string `json:"-"`
Value string `json:"value"`
Error string `json:"error"`
}
func (s RootStruct) MarshalJSON() ([]byte, error) {
data := map[string]interface{}{}
for _, val := range s.Values {
// json keyはvalStruct側のJsonKeyを参照する
data[val.JsonKey] = val
}
return json.Marshal(data)
}
func main() {
s := RootStruct{}
val1 := valStruct{
JsonKey: "key1",
Value: "value1",
}
val2 := valStruct{
JsonKey: "awesome_key",
Value: "value2",
}
val3 := valStruct{
JsonKey: "error_value_key",
Value: "",
Error: "error message",
}
s.Values = append(s.Values, val1)
s.Values = append(s.Values, val2)
s.Values = append(s.Values, val3)
data, _ := json.Marshal(s)
fmt.Println(string(data))
}
実行結果
valStruct
のJsonKeyが利用されてるのがわかる。
{
"awesome_key": {
"value": "value2",
"error": ""
},
"error_value_key": {
"value": "",
"error": "error message"
},
"key1": {
"value": "value1",
"error": ""
}
}