将文件内容存储为多维字符串变量
时间:2024-02-07
浏览:109
作者:佚名
golang学习网今天将给大家带来《将文件内容存储为多维字符串变量》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
问题内容
我正在使用 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: %s\n", info.type) // here is not printing the result of info.type
for _, news := range info.news {
fmt.printf("news name: %s\n", news.name) // here is not printing even "news name:" or news read:"
fmt.printf("news read: %s\n", 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]文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将文件内容存储为多维字符串变量》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.26
热门专题
