golang: Marshal []os.FileInfo into JSON

huangapple go评论81阅读模式
英文:

golang: Marshal []os.FileInfo into JSON

问题

基本上,我想要实现的是通过os.ReadDir()获取目录的内容,然后将结果编码为JSON。

直接使用json.Marshal()没有引发异常,但给出了一个空结果。

所以我尝试了这个:

func (f *os.FileInfo) MarshalerJSON() ([]byte, error) {
    return f.Name(), nil
}

然后Go告诉我os.FileInfo()是一个接口,不能以这种方式进行扩展。

有什么最好的方法可以做到这一点?

英文:

Basically, what I want to achieve is to get the content of a directory via <code>os.ReadDir()</code> and then encode the result into json.

Directly doing <code>json.Marshal()</code> cause no exception but gave me an empty result.

So I tried this:

func (f *os.FileInfo) MarshalerJSON() ([]byte, error) {
    return f.Name(), nil
}

Then Go tells me that <code>os.FileInfo()</code> is an interface and cannot be extended this way.

What's the best way to do this?

答案1

得分: 6

将数据打包到一个可以序列化的结构体中:

type FileInfo struct {
    Name    string
    Size    int64
    Mode    os.FileMode
    ModTime time.Time
    IsDir   bool
}

func main() {
    dir, err := os.Open(".")
    if err != nil {
        log.Fatal(err)
    }
    entries, err := dir.Readdir(0)
    if err != nil {
        log.Fatal(err)
    }

    list := []FileInfo{}

    for _, entry := range entries {
        f := FileInfo{
            Name:    entry.Name(),
            Size:    entry.Size(),
            Mode:    entry.Mode(),
            ModTime: entry.ModTime(),
            IsDir:   entry.IsDir(),
        }
        list = append(list, f)
    }

    output, err := json.Marshal(list)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(output))
}

请注意,这是一个用Go语言编写的代码示例,用于将文件信息打包到一个结构体中,并将其序列化为JSON格式。

英文:

Pack the data into a struct that can be serialized:

http://play.golang.org/p/qDeg2bfik_

type FileInfo struct {
	Name    string
	Size    int64
	Mode    os.FileMode
	ModTime time.Time
	IsDir   bool
}

func main() {
	dir, err := os.Open(&quot;.&quot;)
	if err != nil {
		log.Fatal(err)
	}
	entries, err := dir.Readdir(0)
	if err != nil {
		log.Fatal(err)
	}

	list := []FileInfo{}

	for _, entry := range entries {
		f := FileInfo{
			Name:    entry.Name(),
			Size:    entry.Size(),
			Mode:    entry.Mode(),
			ModTime: entry.ModTime(),
			IsDir:   entry.IsDir(),
		}
		list = append(list, f)
	}

	output, err := json.Marshal(list)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(output))

}

答案2

得分: 1

这是一个不同的版本,使使用看起来很简单。但是你不能将其反序列化回对象。这仅适用于将其发送到客户端或其他地方。

使用方法:

output, err := json.Marshal(FileInfo{entry})

output, err := json.Marshal(FileInfoList{entries})

代码:

type FileInfo struct {
	os.FileInfo
}

func (f FileInfo) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"Name":    f.Name(),
		"Size":    f.Size(),
		"Mode":    f.Mode(),
		"ModTime": f.ModTime(),
		"IsDir":   f.IsDir(),
	})
}

type FileInfoList struct {
	fileInfoList []os.FileInfo
}

//对于相同的结构体多次调用这个函数效率低下
func (f FileInfoList) MarshalJSON() ([]byte, error) {
	fileInfoList := make([]FileInfo, 0, len(f.fileInfoList))
	for _, val := range f.fileInfoList {
		fileInfoList = append(fileInfoList, FileInfo{val})
	}

	return json.Marshal(fileInfoList)
}
英文:

Here is a different version that makes the usage seemingly simple. Though you cannot unmarshall it back to the object. This is only applicable if you are sending it to client-end or something.

http://play.golang.org/p/vmm3temCUn

Usage

output, err := json.Marshal(FileInfo{entry})	

output, err := json.Marshal(FileInfoList{entries})

Code

type FileInfo struct {
	os.FileInfo
}

func (f FileInfo) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		&quot;Name&quot;:    f.Name(),
		&quot;Size&quot;:    f.Size(),
		&quot;Mode&quot;:    f.Mode(),
		&quot;ModTime&quot;: f.ModTime(),
		&quot;IsDir&quot;:   f.IsDir(),
	})
}

type FileInfoList struct {
	fileInfoList []os.FileInfo
}

//This is inefficient to call multiple times for the same struct
func (f FileInfoList) MarshalJSON() ([]byte, error) {
	fileInfoList := make([]FileInfo, 0, len(f.fileInfoList))
	for _, val := range f.fileInfoList {
		fileInfoList = append(fileInfoList, FileInfo{val})
	}

	return json.Marshal(fileInfoList)
}

huangapple
  • 本文由 发表于 2014年9月4日 09:40:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/25656087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定