0

I have the opposite problem as this question.

Decode large stream JSON

In that question, the user asks about decoding a large incoming JSON array.

But, how would I encode a large outgoing JSON array?

For example, I have a http.Handler like this.

enc := json.NewEncoder(resp)
for obj := range objectChannel {
    enc.Encode(obj)
}

However, this doesn't work because it ends up sending invalid JSON to the JavaScript client.

Do I have to manually fix the syntax? For example:

enc := json.NewEncoder(resp)
fmt.Fprint(resp, "[")
for obj := range objectChannel {
    enc.Encode(obj)
    fmt.Fprint(resp, ",") // and account for the last item
}
fmt.Fprint(resp, "]")

Or is there a better way?

425nesp
  • 6,936
  • 9
  • 50
  • 61
  • related to https://github.com/golang/go/issues/7872 ... no solution.. –  May 08 '20 at 21:43
  • as you now use a channel, yes the solution you provided is good because it is simple and efficient. –  May 08 '20 at 21:49
  • 1
    As this is printed into an http responsewriter, dont forget to flush. see https://stackoverflow.com/a/19292461/4466350 –  May 08 '20 at 21:54
  • 1
    Dup of https://stackoverflow.com/questions/18133950/marshaljson-without-having-all-objects-in-memory-at-once – ferhatelmas May 08 '20 at 23:08
  • Yeah, you're right. – 425nesp May 09 '20 at 17:20

1 Answers1

0

If you already have all the objects in memory, there is no point in encoding elements one by one, and you can do:

enc.Encode(lotsOfObjs)

If you get objects one by one, then manually adding [ and ] with commas in between is fine.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59