search
LoginSignup
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

MarshalJSONで任意の変数をJSON keyに使いたい

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": ""
  }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0
Help us understand the problem. What are the problem?