Last active
September 11, 2016 03:55
-
-
Save kentquirk/34bbdaf189b2efb0cf88118b620db427 to your computer and use it in GitHub Desktop.
Go with Data structure
This file contains hidden or 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 ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
) | |
type Pet struct { | |
Owner string `json:"owner"` | |
Pet string `json:"pet"` | |
} | |
func main() { | |
data := bytes.NewBuffer([]byte(`[ | |
{"owner": "Kent", "pet": "Shiner"}, | |
{"owner": "Mary", "pet": "Pumpkin"}, | |
{"owner": "Mary", "pet": "Tasha"}, | |
{"owner": "Paige", "pet": "Sushi"}, | |
{"owner": "Sarah", "pet": "Shiner"}, | |
{"owner": "Sarah", "pet": "Mr. Wigglesworth"}, | |
{"owner": "Sarah", "pet": "Pupparoo"}, | |
{"owner": "Sarah", "pet": "Lucy"} | |
]`)) | |
var input []Pet | |
json.NewDecoder(data).Decode(&input) | |
output := make(map[string][]string) | |
for _, pair := range input { | |
output[pair.Owner] = append(output[pair.Owner], pair.Pet) | |
} | |
json.NewEncoder(os.Stdout).Encode(output) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment