正确创建JSON文件并从中读取

问题描述 投票:0回答:1

我正在尝试使用Golang创建一个JSON文件。我对JSON文件知之甚少并创建它们但我创建了一个创建它们的程序。在此程序中,它从网站获取表单数据,然后将数据放入JSON结构中,然后将信息添加到文件夹中。我这里有2节数据。我在错误发生的地方发表了评论

{
    "cl":"[v1]",
    "gr":"[A]",
    "cr":"[8]"
} // End Of File Expected
{
    "cl":"[v2]",
    "gr":"[Z]",
    "cr":"[8]"
}

所以我的问题是(1)错误意味着什么,以及(2)在使用Golang创建JSON文件时如何/我可以解决这个问题?如果需要,我可以提供Golang。

json go
1个回答
2
投票

所以除了json没有正确格式化之外,这里有一个如何使用struct和json struct标签创建json的示例。

适当的JSON

[{key:value,key value},{key:value,key value}]

你拥有的是{key:value,key value} {key:value,key value}

这是两个单独的对象,而不是数组中的一个对象。

如果您正在从文件中读取此数据并且返回的数据与您的示例类似,那么您可能必须在换行符上拆分以分隔每个对象并单独解组它们。

否则以下应该以服务器为例。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "strconv"
)

type j struct {
    Cl []string `json:"cl"`
    Gr []string `json:"gr"`
    Cr []string `json:"cr"`
}

func main() {
    // create an instance of j as a slice
    var data []j
    // using a for loop for create dummy data fast
    for i := 0; i < 5; i++ {
        v := strconv.Itoa(i)
        data = append(data, j{
            Cl: []string{"foo " + v},
            Gr: []string{"bar " + v},
            Cr: []string{"foobar " + v},
        })
    }

    // printing out json neatly to demonstrate
    b, _ := json.MarshalIndent(data, "", " ")
    fmt.Println(string(b))

    // writing json to file

    _ = ioutil.WriteFile("file.json", b, 0644)

    // to append to a file
    // create the file if it doesn't exists with O_CREATE, Set the file up for read write, add the append flag and set the permission
    f, err := os.OpenFile("/var/log/debug-web.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
    if err != nil {
        log.Fatal(err)
    }
    // write to file, f.Write()
    f.Write(b)

    // if you are doing alot of I/O work you may not want to write out to file often instead load up a bytes.Buffer and write to file when you are done... assuming you don't run out of memory when loading to bytes.Buffer


}
© www.soinside.com 2019 - 2024. All rights reserved.