将json对象写入文件

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

json对象写入文件有这样的工作流程:

for {
    Step 1. create json object
    Step 2. Save object to file
}

所以我写了这样的代码

f, _ := os.Create("output.json")
defer f.Close()
a1 := A{Name:"John", Surname:"Black"}
a2 := A{Name:"Mary", Surname:"Brown"}

a1_json, _ := json.MarshalIndent(a1, "", "\t")
a2_json, _ := json.MarshalIndent(a2, "", "\t")
f.Write(a1_json)
f.Write(a2_json)

结果我有:

{
    "Name": "John",
    "Surname": "Black"
}{
    "Name": "Mary",
    "Surname": "Brown"
}

这是不正确的json文件,因为它没有开关括号和逗号这样:

[
  {
    "Name": "John",
    "Surname": "Black"
  },
  {
    "Name": "Mary",
    "Surname": "Brown"
  }
]

如何以适当的方式写入文件?

json go io
2个回答
3
投票

只需制作一块结构并保存即可。这将创建JSON数组。

f, _ := os.Create("output.json")
defer f.Close()
as := []A{
    {Name:"John", Surname:"Black"},
    {Name:"Mary", Surname:"Brown"},
}
as_json, _ := json.MarshalIndent(as, "", "\t")
f.Write(as_json)

如果你真的想要你可以手动分离元素。

f, _ := os.Create("output.json")
defer f.Close()
a1 := A{Name:"John", Surname:"Black"}
a2 := A{Name:"Mary", Surname:"Brown"}

f.Write([]byte("[\n"))
a1_json, _ := json.MarshalIndent(a1, "", "\t")
f.Write([]byte(",\n"))
a2_json, _ := json.MarshalIndent(a2, "", "\t")
f.Write([]byte("]\n"))

f.Write(a1_json)
f.Write(a2_json)

您也可以考虑使用可以实现目标的JSON Streaming,但语法略有不同。


1
投票

将这些结构放入切片中,然后对切片进行编组

f, err := os.Create("output.json")
if err != nil{
   panic(err)
}
defer f.Close()
a1 := A{Name:"John", Surname:"Black"}
a2 := A{Name:"Mary", Surname:"Brown"}

a := []A{a1, a2}
a_json, err := json.MarshalIndent(a, "", "\t")
if err != nil{
   panic(err)
}
f.Write(a_json)

此外,请尽可能检查err

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