dtjpz48440 2015-12-21 03:58
浏览 275

在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.

  • 写回答

2条回答 默认 最新

  • dongmei425373 2015-12-21 04:04
    关注

    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, "")
    

    <kbd>run the code on the playground</kbd>

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型