英文:
reading file and putting json file in Nested structure in Go lang with appending extra data
问题
我有一个嵌套结构,一个结构来自读取文件,另一个是我自己提供的,我需要将文件输出到标准输出。我已经有了代码,但是对于语法和逻辑我感到很困惑,因为我是Go语言的新手。(数据结构应该来自文件)
英文:
I have nested structure one structure coming from reading file and second I'm providing my self and I have to stdout the file. I got the code but I'm having hard time with syntax and logic I'm new to go lang.(the data structure supposed to come from the file)
答案1
得分: 1
程序读取文件,然后用其他内容替换数据。只需将数据放入输出的值中。
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"` /* <= 更改为字符串 */
}
func main() {
if len(os.Args) < 1 { // 检查是否提供了参数,如果第一个参数满足条件,则使用读取文件
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: "", // 用户输入 -p 或 -u
Time: time.Now(),
Data: string(Data), /* <= 将数据放入输出值中 */
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
}
也许输出中的 \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"` /* <= 更改为 json.RawMessage */
}
func main() {
if len(os.Args) < 1 { // 检查是否提供了参数,如果第一个参数满足条件,则使用读取文件
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: "", // 用户输入 -p 或 -u
Time: time.Now(),
Data: Data, /* <= 使用原始数据 */
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
}
在 playground 上运行以查看嵌套的 JSON。你在问题中显示了一个带引号的字符串,但也许这个输出才是你真正想要的。
英文:
The program reads the file, but then substitutes something else in for data. Just put the data in the value marshaled to the output.
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.
Perhaps the \r\n in the output are the problem. Remove carriage return and line feed from the JSON before encoding the result:
replacer := strings.NewReplacer("\r", "", "\n", "")
Data = []byte(replacer.Replace(string(Data)))
If you intent is to include the JSON as JSON instead of quoting the JSON as string, then use 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. You show a quoted string in the question, but perhaps this output is what you really want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论