Created
November 20, 2022 16:09
-
-
Save 178inaba/360b48438b5a10135331b20d75134fb1 to your computer and use it in GitHub Desktop.
DB to JSON by Go.
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 ( | |
"encoding/json" | |
"log" | |
"os" | |
"github.com/brianvoe/gofakeit/v6" | |
) | |
type UserValue struct { | |
ID int | |
Name string | |
Address string | |
} | |
type User struct { | |
ID int `json:"id"` | |
Name string `json:"name"` | |
Addresses []string `json:"addresses"` | |
} | |
func main() { | |
var uvs []*UserValue | |
for i := 0; i < 1000; i++ { | |
id := i + 1 | |
name := gofakeit.Name() | |
for j := 0; j < 100; j++ { | |
uvs = append(uvs, &UserValue{ | |
ID: id, | |
Name: name, | |
Address: gofakeit.Address().Address, | |
}) | |
} | |
} | |
m := map[int]*User{} | |
for _, uv := range uvs { | |
if _, ok := m[uv.ID]; !ok { | |
m[uv.ID] = &User{ | |
ID: uv.ID, | |
Name: uv.Name, | |
} | |
} | |
m[uv.ID].Addresses = append(m[uv.ID].Addresses, uv.Address) | |
} | |
var us []*User | |
for _, v := range m { | |
us = append(us, v) | |
} | |
if err := json.NewEncoder(os.Stdout).Encode(us); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment