将 JSON 结构附加到 JSON 文件 Golang



我有一个用户的JSON文档,他们有ID#,电话#和电子邮件。输入另一个ID,电话和电子邮件后,我想获取新用户的信息并将其附加到文件中。我有一个结构,只包含一个 {ID: #, 电话: #, 电子邮件: #} 并且工作正常。但是我的 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"}]

所以我能够附加到文档中,但它是一个用括号 [] 括起来的新 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)
    }
}

这可能有用,这是我的识别结构。

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"}
    ]

要实现输出,请按如下方式定义结构-

type Identification struct {
   ID    string
   Phone int64
   Email string
}

并按如下方式进行操作-

// 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

上述说明 https://play.golang.org/p/67dqOaCWHI 的示例程序

最新更新