Skip to content

Instantly share code, notes, and snippets.

@buzztaiki
Last active July 14, 2022 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzztaiki/1b88c2ce73dfa0fdacebe4647171ad13 to your computer and use it in GitHub Desktop.
Save buzztaiki/1b88c2ce73dfa0fdacebe4647171ad13 to your computer and use it in GitHub Desktop.
キーの名前にルールはあるけど一定じゃないキーがあるJSONをデコードするやつ
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Payload struct {
PayloadContents
Sites map[string]Site `json:"-"`
}
type PayloadContents struct {
ID string
}
type Site struct {
Name string
}
func (p *Payload) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &p.PayloadContents); err != nil {
return fmt.Errorf("failed to decode contents", err)
}
rawSites := map[string]json.RawMessage{}
if err := json.Unmarshal(b, &rawSites); err != nil {
return fmt.Errorf("failed to decode sites", err)
}
p.Sites = map[string]Site{}
for k, v := range rawSites {
if !strings.HasPrefix(k, "https://") {
continue
}
site := Site{}
if err := json.Unmarshal(v, &site); err != nil {
return fmt.Errorf("failed to decode site %q: %w", k, err)
}
p.Sites[k] = site
}
return nil
}
func main() {
jsonText := `
{
"https://www.google.com": {"name": "google"},
"https://www.mozila.org": {"name": "mozilla"},
"id": "moo"
}`
payload := Payload{}
if err := json.Unmarshal([]byte(jsonText), &payload); err != nil {
log.Fatalf("failed do decode paylaod: %+v", err)
}
fmt.Printf("%+v", payload)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment