2

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.

1
  • Thanks for the edit voutasaurus. Commented Dec 23, 2015 at 16:07

2 Answers 2

3

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\n", 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

Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly - many thanks. I didn't consider a recursive call into the printing function itself, which of course now is an obvious solution.
2

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
  ]
}

2 Comments

Thanks, but json.MarshalIndent outputs JSON (as it should). I was looking for a plain text output that's more human readable.
Though this doesn't answer the question, I upvoted it because it was the first result on Google where I was looking for exactly this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.