arrays - 自己结构数组的JSON编码

标签 arrays json struct go encoder

我尝试读取一个目录并从文件条目中生成一个 JSON 字符串。但是 json.encoder.Encode() 函数只返回空对象。为了测试,我在 tmp 目录中有两个文件:

test1.js  test2.js 

go程序是这样的:

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "path/filepath"
    "time"
)

type File struct {
    name      string
    timeStamp int64
}

func main() {

    files := make([]File, 0, 20)

    filepath.Walk("/home/michael/tmp/", func(path string, f os.FileInfo, err error) error {

        if f == nil {
            return nil
        }

        name := f.Name()
        if len(name) > 3 {
            files = append(files, File{
                name:      name,
                timeStamp: f.ModTime().UnixNano() / int64(time.Millisecond),
            })

            // grow array if needed
            if cap(files) == len(files) {
                newFiles := make([]File, len(files), cap(files)*2)
                for i := range files {
                    newFiles[i] = files[i]
                }
                files = newFiles
            }
        }
        return nil
    })

    fmt.Println(files)

    encoder := json.NewEncoder(os.Stdout)
    encoder.Encode(&files)
}

它产生的结果是:

[{test1.js 1444549471481} {test2.js 1444549481017}]
[{},{}]

为什么JSON字符串是空的?

最佳答案

它不起作用,因为没有导出 File 结构中的任何字段。

以下工作正常:

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "path/filepath"
    "time"
)

type File struct {
    Name      string
    TimeStamp int64
}

func main() {

    files := make([]File, 0, 20)

    filepath.Walk("/tmp/", func(path string, f os.FileInfo, err error) error {

        if f == nil {
            return nil
        }

        name := f.Name()
        if len(name) > 3 {
            files = append(files, File{
                Name:      name,
                TimeStamp: f.ModTime().UnixNano() / int64(time.Millisecond),
            })

            // grow array if needed
            if cap(files) == len(files) {
                newFiles := make([]File, len(files), cap(files)*2)
                for i := range files {
                    newFiles[i] = files[i]
                }
                files = newFiles
            }
        }
        return nil
    })

    fmt.Println(files)
    encoder := json.NewEncoder(os.Stdout)
    encoder.Encode(&files)
}

关于arrays - 自己结构数组的JSON编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062750/

相关文章:

从 url 解析 xml 文件时发生 java 错误

json - Powershell 解析 Swagger Json

c - 我不需要 malloc() 这个数组吗?

c - 从双指针访问结构

arrays - 戈朗 : using nested structs

c++ - C++ 中 `a` 和 `&a` 之间的区别,其中 `a` 是一个数组

c# - 将字段放入下一个空数组索引

javascript - 考虑另一个数组的索引来拼接数组中的项目

java - 如何使用GSON获取解析后的数据

python - Shapefile 到 geojson 转换 python 3