将文件内容存入多维字符串变量中。

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

Getting file content into a multidimensional string 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
}

// 主函数
func main() {
   // 使用fsnotify读取json文件并等待更改
	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("文件信息:\n") 

				for _, info := range data.Info {
                    fmt.Printf("信息类型:%s\n", info.Type) // 这里没有打印info.Type的结果
					for _, news := range info.News {
						fmt.Printf("新闻名称:%s\n", news.Name) // 这里甚至没有打印"新闻名称:"或"新闻已读:"
                        fmt.Printf("新闻已读:%s\n", strconv.FormatBool(news.Read))
					}
				}
			}
		case err := <-watcher.Errors:
			log.Println("错误:", 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 }
            ]
        }
    ]
}
英文:

I'm using the fsnotify packet to wait for changes in a json file.

I have two problems with this code. The first one is regarding the info returned by ReadFile function. Looks like when I print something returned by the function is empty.

Second issue is regarding the fsnotify that is not reading the file the first time unless i do some modification on the content. I must read the file from the beggining as well.

type Information struct {
Info []Info `json:&quot;info&quot;`
}
type Info struct {
Type string `json:&quot;type&quot;`
News []New  `json:&quot;news&quot;`
}
type New struct {
Name string `json:&quot;name&quot;`
Read bool   `json:&quot;read&quot;`
}
func ReadFile(file_name string) *Information {
jsonFile, err := os.Open(file_name)
if err != nil {
fmt.Println(err)
}
fmt.Println(&quot;Successfully Opened file_name.json&quot;)
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var infor Information
json.Unmarshal(byteValue, &amp;infor)
return &amp;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 := &lt;-watcher.Events:
log.Println(&quot;event:&quot;, ev)
if !ok {
return
}
if ev.Op&amp;fsnotify.Write == fsnotify.Write {
data := ReadFile(file_name)
fmt.Print(&quot;INFORMATION ABOUT FILE:\n&quot;) 
for _, info := range data.Info {
fmt.Printf(&quot;Info type: %s\n&quot;, info.Type) // Here is not printing the result of info.Type
for _, news := range info.News {
fmt.Printf(&quot;News Name: %s\n&quot;, news.Name) // Here is not printing even &quot;News Name:&quot; or News Read:&quot;
fmt.Printf(&quot;News Read: %s\n&quot;, strconv.FormatBool(news.Read))
}
}
}
case err := &lt;-watcher.Errors:
log.Println(&quot;error:&quot;, err)
}
}
}

This is the json file:

{
&#160;&#160;&#160; &quot;info&quot;: [
&#160;&#160;&#160;&#160;&#160; {
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &quot;type&quot;: &quot;general&quot;,
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &quot;news&quot;: [
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &quot;name&quot;: &quot;abc&quot;,&#160; &quot;read&quot;: true },
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &quot;name&quot;: &quot;def&quot;,&#160; &quot;read&quot;: true }
&#160;&#160;&#160;&#160;&#160;&#160;&#160; ]
&#160;&#160;&#160;&#160;&#160; },
{
&quot;type&quot;: &quot;confidential&quot;,
&quot;news&quot;: [
{ &quot;name&quot;: &quot;xxx&quot;,  &quot;read&quot;: false },
{ &quot;name&quot;: &quot;yyy&quot;,  &quot;read&quot;: false }
]
},
]
}

答案1

得分: 1

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("成功打开文件 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
			// 添加你想要做的操作
			fmt.Println(name)
		}
	}
}

不能得到这样的结果:

getInfo = [general][abc, true, def, true]
[confidential][xxx, false, yyy, false]
英文:
type Information struct {
	Info []Info `json:&quot;info&quot;`
}

type Info struct {
	Type string `json:&quot;type&quot;`
	News []New  `json:&quot;news&quot;` // Here should be a slice define.
}

type New struct {
	Name string `json:&quot;name&quot;`
	Read bool   `json:&quot;read&quot;`
}

func ReadFile(file_name string) *Information {
	jsonFile, err := os.Open(file_name)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(&quot;Successfully Opened file_name.json&quot;)

	defer jsonFile.Close()

	byteValue, _ := ioutil.ReadAll(jsonFile)

	var infor Information

	json.Unmarshal(byteValue, &amp;infor)

	return &amp;infor
}
func main() {
	data := ReadFile(&quot;./data.json&quot;)
	for _, news := range data.Info {
		for _, v := range news.News {
			name := v.Name
			// Add you want to do
			fmt.Println(name)
		}
	}
}

You can not get like this:

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

huangapple
  • 本文由 发表于 2022年6月27日 19:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/72771038.html
匿名

发表评论

匿名网友

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

确定