在Go中读取并解析JSON文件,将其放入嵌套结构中,并添加额外数据
时间:2024-02-07
浏览:217
作者:佚名
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《在Go中读取并解析JSON文件,将其放入嵌套结构中,并添加额外数据》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
问题内容
我已经嵌套了一个结构,一个结构来自读取文件,第二个我提供我自己,我必须输出该文件。我得到了代码,但我在语法和逻辑上遇到了困难,我是语言新手。(数据结构应该来自文件)
正确答案
程序读取文件,然后用其他内容替换数据。只需将数据放入编组到输出的值中即可。
type event struct {
specversion string `json:"specversion"`
id uuid.uuid `json:"id"` /// uuid
source string `json:"source"`
type string `json:"type"`
time time.time `json:"time"`
data string `json:"data"` /* <= change to string */
}
func main() {
if len(os.args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.println("usage : " + os.args[0] + " file name")
help()
os.exit(1)
}
data, err := ioutil.readfile(os.args[1])
if err != nil {
fmt.println("cannot read the file or file does not exists")
os.exit(1)
}
e := event{
specversion: "1.0",
id: uuid.new(),
source: "css",
type: "", // user input -p or -u,
time: time.now(),
data: string(data), /* <= stuff data into output value */
}
out, _ := json.marshalindent(e, "", " ")
fmt.println(string(out))
}
Run it on the playground to get results as requested in the question。
也许输出中的 \r\n 是问题所在。在对结果进行编码之前,从 json 中删除回车符和换行符:
replacer := strings.newreplacer("\r", "", "\n", "")
data = []byte(replacer.replace(string(data)))
如果您打算将 json 作为 json 包含在内,而不是将 json 作为字符串引用,则使用 json.RawMessage:
type Event struct {
Specversion string `json:"specversion"`
ID uuid.UUID `json:"id"` /// uuid
Source string `json:"source"`
Type string `json:"type"`
Time time.Time `json:"time"`
Data json.RawMessage `json:"data"` /* <= change to json.RawMessage */
}
func main() {
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
Data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
e := Event{
Specversion: "1.0",
ID: uuid.New(),
Source: "CSS",
Type: "", // user input -p or -u,
Time: time.Now(),
Data: Data, /* <== use data as is */
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
}
Run it on the playground to view nested json。您在问题中显示了带引号的字符串,但也许这个输出才是您真正想要的。
以上就是《在Go中读取并解析JSON文件,将其放入嵌套结构中,并添加额外数据》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
热门专题
