Last active
July 14, 2022 13:26
-
-
Save buzztaiki/1b88c2ce73dfa0fdacebe4647171ad13 to your computer and use it in GitHub Desktop.
キーの名前にルールはあるけど一定じゃないキーがあるJSONをデコードするやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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