英文:
Converting a JSON dir tree into indented plain text in GoLang
问题
我有一个以JSON结构表示的目录树,我想要将其格式化为纯文本。在XML或YAML中进行格式化相对容易,但在纯文本中进行格式化比我想象的要困难得多。
JSON结构的格式如下:
type File struct {
Name string `json:"Name"`
Children []*File `json:"Children"`
}
由于JSON结构允许有"children",所以JSON是嵌套的,而且由于它是一个目录树,我不知道嵌套会有多深(在合理范围内)。
我需要转换后的JSON看起来像这样:
base_dir
sub_dir_1
sub_dir_2
file_in_sub_dir_2
sub_dir_3
...
有人能告诉我如何以相对简单的方式实现这个目标吗?目前我只能使用大量循环和制表符进行强制缩进,但我确信在Go语言中有更优雅的方式。
英文:
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
得分: 3
编写一个函数来递归遍历目录树,打印文件及其子文件。在递归遍历树时增加缩进级别。
func printFile(f *File, indent string) {
fmt.Printf("%s%s\n", indent, f.Name)
for _, f := range f.Children {
printFile(f, indent+" ")
}
}
使用树的根节点调用该函数:
printFile(root, "")
英文:
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, "")
<kbd>run the code on the playground</kbd>
答案2
得分: 2
你可以使用MarshalIndent来实现这个功能。这里有一个<kbd>go playground</kbd>的示例。
instance := MyStruct{12344, "ohoasdoh", []int{1, 2, 3, 4, 5}}
res, _ := json.MarshalIndent(instance, "", " ")
fmt.Println(string(res))
这将会得到如下结果:
{
"Num": 12344,
"Str": "ohoasdoh",
"Arr": [
1,
2,
3,
4,
5
]
}
英文:
You can achieve this with MarshalIndent. Here is a <kbd>go playground</kbd> 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
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论