【问题标题】:JSON encode of array of own struct自己结构数组的 JSON 编码
【发布时间】:2016-01-08 20:20:33
【问题描述】:

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

test1.js  test2.js 

围棋程序是这样的:

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 字符串是空的?

【问题讨论】:

  • JSON 编码需要 exported 字段名称,例如 NameTimestamp。这是重复的。 encoding/json 清楚地表明只有导出的字段是 de/encodable。在 SO 上,她至少被问过十次。

标签: arrays json struct go encoder


【解决方案1】:

它不起作用,因为没有导出 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)
}

【讨论】:

  • 如果这样做,您可以保留原始名称:Name string `json:"name"`TimeStamp int64 `json:"timeStamp"`--这对于导出更多惯用的 json 很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多