0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

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

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
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?