mkiuchi
mkiuchi

Reputation: 1

How to stringify io.FileInfo

I want to return array of io.FileInfo in JSON format, but json.Marshal returns nil. Is there any good way to do that?

package main

import (
    "fmt"
    "io/ioutil"
    "encoding/json"
)

func main () {
    dirlist, _ := ioutil.ReadDir("/var/tmp")
    retstr, _ := json.Marshal(dirlist)
    fmt.Println(string(retstr))
}

Above codes returns [{},{},{},{},{},{},{},{},{},{},{}]

Upvotes: 0

Views: 274

Answers (1)

Thundercat
Thundercat

Reputation: 120979

The os.FileInfo values marshal as empty objects because the file info fields are not exported.

Declare a type with exported fields corresponding to each FileInfo method:

type fileInfo struct {
    Name    string      // base name of the file
    Size    int64       // length in bytes for regular files; system-dependent for others
    Mode    os.FileMode // file mode bits
    ModTime time.Time   // modification time
    IsDir   bool        // abbreviation for Mode().IsDir()
}

Copy the []os.FileInfo to a []fileInfo and marshal the []fileInfo.

fis := make([]fileInfo, len(dirlist))
for i, fi := range dirlist {
    fis[i] = fileInfo{
        Name:    fi.Name(),
        Size:    fi.Size(),
        Mode:    fi.Mode(),
        ModTime: fi.ModTime(),
        IsDir:   fi.IsDir(),
    }
}
retstr, _ := json.Marshal(fis)

Run it on the playground.

Upvotes: 1

Related Questions