在GoLang中将JSON目录树转换为缩进的纯文本

I have a dir tree in a JSON struct that I'm trying to format in plain text. Formatting it in XML or YAML is pretty easy. Formatting it in plain text is much harder than I thought.

The JSON struct is formatted like this :

type File struct {
   Name     string  `json:"Name"`
   Children []*File `json:"Children"`
}

Since the JSON structure allows for 'children', the JSON is nested, and since it's a dir tree, I don't know how deep the nesting will get (within reason).

I need the converted JSON to look like this :

base_dir
  sub_dir_1
  sub_dir_2
    file_in_sub_dir_2
  sub_dir_3
  ...

Can anyone tell me how this could be done in a reasonably simple way? Right now I'm having to brute force with lots of looping and indenting with tabs, and I'm just sure there's a more elegant way in Go.

Write a function to recurse down the directory tree printing a file and its children. Increase the indent level when recursing down the tree.

func printFile(f *File, indent string) {
   fmt.Printf("%s%s
", indent, f.Name)
   for _, f := range f.Children {
     printFile(f, indent+"  ")
   }
}

Call the function with the root of the tree:

printFile(root, "")

run the code on the playground

You can achieve this with MarshalIndent. Here is a go playground example.

instance := MyStruct{12344, "ohoasdoh", []int{1, 2, 3, 4, 5}}
res, _ := json.MarshalIndent(instance, "", "  ")
fmt.Println(string(res))

Which will give you something like:

{
  "Num": 12344,
  "Str": "ohoasdoh",
  "Arr": [
    1,
    2,
    3,
    4,
    5
  ]
}