Kenenbek Arzymatov
Kenenbek Arzymatov

Reputation: 9139

Writing json objects to file

There is such workflow of writing json objects to file :

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

So I wrote such code

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)

As a result I have:

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

Which is not correct json file, because it doesn't have opening and closing braces and comma like this:

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

How can I write to file in an appropriate way?

Upvotes: 2

Views: 3007

Answers (2)

Grzegorz Żur
Grzegorz Żur

Reputation: 49251

Just make a slice of the structures and save it. This will create the JSON array.

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)

If you really want you can separate the elements manually.

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)

You can also consider using JSON Streaming which can achieve your goals but the syntax is slightly different.

Upvotes: 3

vedhavyas
vedhavyas

Reputation: 1151

Put those structs into a slice and marshall the slice instead

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)

Also, always check for err wherever possible

Upvotes: 1

Related Questions