【问题标题】:How to create hierarchical json structure by slice string path如何通过切片字符串路径创建分层 json 结构
【发布时间】:2021-09-07 14:34:32
【问题描述】:

我正在为用 Go 编写的文件管理器构建一个后端。

我正在寻找一种方法来制作示例切片字符串路径。

sliceStr := []string{
   "/file_A.txt",
   "/folder_B/file_B.txt",
   "/folder_C/sub_folder_C/file_C.txt",
   "/folder_C/sub_folder_C/file_C_2.txt",
}

创建一个返回分层 json 结构的 api,以使用 Devextreme FileManager 传递给前端。如下所示

[
    {
        "name": "file_A.txt",
        "isDirectory": false
    },
    {
        "name": "folder_B",
        "isDirectory": true,
        "items": [
            {
                "name": "file_B.txt",
                "isDirectory": false
            }
        ]
    },
    {
        "name": "folder_C",
        "isDirectory": true,
        "items": [
            {
                "name": "sub_folder_C",
                "isDirectory": true,
                "items": [
                    {
                        "name": "file_C.txt",
                        "isDirectory": false,
                    },
                    {
                        "name": "file_C_2.txt",
                        "isDirectory": false
                    }
                ]
            }
        ]
    }
]

【问题讨论】:

  • 我写了一个小模块,基本上就是这样做的。但它使用点作为分隔符而不是斜线。 github.com/bluebrown/labelparser。您可以根据自己的喜好对其进行修改。也许它有助于理解这个想法。

标签: json go


【解决方案1】:

你可以试试这个方法

  • 将切片加入字节数组
  • 实现你自己的 json UnmarshalJSON
type  Yourstruct  struct {
    .......
}
func (t *Yourstruct ) UnmarshalJSON(data []byte) error 

demo case

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2014-09-06
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多