将json对象写入文件

时间:2018-03-06 11:43:27

标签: json go io

有将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" } ] ,因为它没有这样的开括号和右括号和逗号:

TextView

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

2 个答案:

答案 0 :(得分: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 :(得分: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