Created
September 4, 2020 16:10
-
-
Save Qs-F/6981ae28aaa1ec6263947f689d289f19 to your computer and use it in GitHub Desktop.
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" | |
"fmt" | |
"path/filepath" | |
"strings" | |
) | |
type Input struct { | |
Key string `json:"key"` | |
} | |
type Child map[string]Child | |
func (c Child) Push(entry string) Child { | |
if _, ok := c[entry]; !ok { | |
c[entry] = make(Child) | |
} | |
return c[entry] | |
} | |
type Output struct { | |
Name string `json:"name,omitempty"` | |
Child []*Output `json:"child,omitempty"` | |
} | |
func (c Child) Conv() []*Output { | |
if c == nil { | |
return nil | |
} | |
ret := []*Output{} | |
for k, v := range c { | |
ret = append(ret, &Output{Name: k, Child: v.Conv()}) | |
} | |
return ret | |
} | |
func main() { | |
inputs := []*Input{} | |
err := json.Unmarshal(test, &inputs) | |
if err != nil { | |
println(err.Error()) | |
} | |
root := make(Child) | |
for _, input := range inputs { | |
curr := root | |
for _, e := range strings.Split(input.Key, string(filepath.Separator)) { | |
curr = curr.Push(e) | |
} | |
} | |
b, err := json.Marshal(root.Conv()) | |
if err != nil { | |
println(err.Error()) | |
} | |
fmt.Println(string(b)) | |
} | |
var test = []byte(` | |
[ | |
{"key":"a/b/c.json"}, | |
{"key":"a/b/d.json"}, | |
{"key":"b/c/f.json"}, | |
{"key":"b/f/g.json"}, | |
{"key":"x/y/z/"} | |
]`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment