Roh*_*kar 6 json file go file-writing
我有一个用户的 JSON 文档,其中有 ID#、电话#和电子邮件。在输入另一个 ID、电话和电子邮件时,我想获取新用户的信息并将其附加到文件中。我有一个只包含 {ID: #, Phone: #, Email: #} 的结构,并且工作正常。但是我的 JSON 文件变成了这样:
[{"ID":"ABCD","Phone":1234567890,"Email":"johndoe@test.com"}]
[{"ID":"EFGH","Phone":1234567890,"Email":"johndoe@test.com"}]
[{"ID":"IJKL","Phone":1234567890,"Email":"johndoe@test.com"}]
[{"ID":"MNOP","Phone":1234567890,"Email":"johndoe@test.com"}]
[{"ID":"QRST","Phone":1234567890,"Email":"johndoe@test.com"}]
[{"ID":"UVWX","Phone":1234567890,"Email":"johndoe@test.com"}]
Run Code Online (Sandbox Code Playgroud)
所以我可以附加到文档中,但它是一个用方括号 [] 括起来的新 JSON 结构。下面是我的代码。我省略了实际的散列 ID。
func ToIds(e string, p int64) {
hashed := GenId()
var jsonText = []byte(`[
{"ID": "", "Phone": 0, "Email": ""}
]`)
var I Identification
err := json.Unmarshal([]byte(jsonText), &I)
if err != nil {
fmt.Println(err)
}
I[0].ID = hashed
I[0].Phone = p
I[0].Email = e
result, error := json.Marshal(I)
if error != nil {
fmt.Println(error)
}
f, erro := os.OpenFile("FILE_PATH", os.O_APPEND|os.O_WRONLY, 0666)
if erro != nil {
fmt.Println(erro)
}
n, err := io.WriteString(f, string(result))
if err != nil {
fmt.Println(n, err)
}
}
Run Code Online (Sandbox Code Playgroud)
这可能有用,这是我的识别结构。
type Identification []struct {
ID string
Phone int64
Email string
}
本质上,我想要外面的括号,在这些括号内我想附加多个用户。像这样的东西:
[
{"id":"A", "phone":17145555555, "email":"tom@gmail.com"},
{"id":"B","phone":15555555555,"email":"p@gmail.com"},
{"id":"C","phone":14155555555,"email":"bradley@gmail.com"},
{"id":"D","phone":17135555555,"email":"g@gmail.com"},
{"id":"E","phone":17125555555,"email":"ann@gmail.com"},
{"id":"F","phone":17125555555,"email":"sam@gmail.com"},
{"id":"G","phone":14055555555,"email":"john@gmail.com"},
{"id":"H","phone":13105555555,"email":"lisa@gmail.com"}
]
Run Code Online (Sandbox Code Playgroud)
要实现您的输出,请按如下方式定义 struct-
type Identification struct {
ID string
Phone int64
Email string
}
Run Code Online (Sandbox Code Playgroud)
并执行如下操作-
// define slice of Identification
var idents []Identification
// Unmarshall it
err := json.Unmarshal([]byte(jsonText), &idents)
// add further value into it
idents = append(idents, Identification{ID: "ID", Phone: 15555555555, Email: "Email"})
// now Marshal it
result, error := json.Marshal(idents)
// now result has your targeted JSON structure
Run Code Online (Sandbox Code Playgroud)
以上解释的示例程序https://play.golang.org/p/67dqOaCWHI