将文件内容转换为多维字符串var



我正在使用fsnotify数据包等待json文件中的更改。

这段代码有两个问题。第一个问题是关于ReadFile函数返回的信息。看起来当我打印函数返回的东西是空的。

第二个问题是关于fsnotify第一次不读取文件,除非我对内容做了一些修改。我必须从头开始读这个文件。

type Information struct {
Info []Info `json:"info"`
}
type Info struct {
Type string `json:"type"`
News []New  `json:"news"`
}
type New struct {
Name string `json:"name"`
Read bool   `json:"read"`
}
func ReadFile(file_name string) *Information {
jsonFile, err := os.Open(file_name)
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened file_name.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var infor Information
json.Unmarshal(byteValue, &infor)
return &infor
}
// main function
func main() {
// read json file using fsnotify to wait for changes
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
err = watcher.Add(file_json)
if err != nil {
panic(err)
}
for {
select {
case ev, ok := <-watcher.Events:
log.Println("event:", ev)
if !ok {
return
}
if ev.Op&fsnotify.Write == fsnotify.Write {
data := ReadFile(file_name)
fmt.Print("INFORMATION ABOUT FILE:n") 
for _, info := range data.Info {
fmt.Printf("Info type: %sn", info.Type) // Here is not printing the result of info.Type
for _, news := range info.News {
fmt.Printf("News Name: %sn", news.Name) // Here is not printing even "News Name:" or News Read:"
fmt.Printf("News Read: %sn", strconv.FormatBool(news.Read))
}
}
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}

这是json文件:

{
    "info": [
      {
        "type": "general",
        "news": [
          { "name": "abc",  "read": true },
          { "name": "def",  "read": true }
        ]
      },
{
"type": "confidential",
"news": [
{ "name": "xxx",  "read": false },
{ "name": "yyy",  "read": false }
]
},
]
}
type Information struct {
Info []Info `json:"info"`
}
type Info struct {
Type string `json:"type"`
News []New  `json:"news"` // Here should be a slice define.
}
type New struct {
Name string `json:"name"`
Read bool   `json:"read"`
}
func ReadFile(file_name string) *Information {
jsonFile, err := os.Open(file_name)
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened file_name.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var infor Information
json.Unmarshal(byteValue, &infor)
return &infor
}
func main() {
data := ReadFile("./data.json")
for _, news := range data.Info {
for _, v := range news.News {
name := v.Name
// Add you want to do
fmt.Println(name)
}
}
}

不能像这样:

getInfo = [general][abc, true, def, true]
[confidential][xxx, false, yyy, false]

相关内容

  • 没有找到相关文章

最新更新