自定义结构体数组的JSON编码。

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

JSON encode of array of own struct

问题

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

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

英文:

I try to read a directory and make a JSON string out of the file entries. But the json.encoder.Encode() function returns only empty objects. For test I have two files in a tmp dir:

test1.js  test2.js 

The go program is this:

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)
}

And the out that it produces is:

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

Why is the JSON string empty?

答案1

得分: 2

这是你要翻译的内容:

由于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)
}
英文:

It doesn't work because none of the fields in the File struct are exported.

The following works just fine:

<!-- language: lang-golang -->

package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;os&quot;
    &quot;path/filepath&quot;
    &quot;time&quot;
)

type File struct {
    Name      string
    TimeStamp int64
}

func main() {

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

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

        if f == nil {
            return nil
        }

        name := f.Name()
        if len(name) &gt; 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(&amp;files)
}

huangapple
  • 本文由 发表于 2015年10月11日 15:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/33062750.html
匿名

发表评论

匿名网友

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

确定