How to customize indent function during json.Marshal?

520 Views Asked by At

We have designed an "export" API which enables users to download a json file with information. The json is an array. Now we meet a little dilemma.

Call json.Marshal directly (no indent, not so user-friendly)

[{"foo":"bar"},{"foo1":"bar1"}]

Call json.MarshalIndent, or json.Indent(dst, src, "", " ") (too much indent)

[
  {
    "foo": "bar"
  },
  {
    "foo1": "bar1"
  }
]

I want this kind

[
  {"foo": "bar"},
  {"foo1": "bar1"}
]

Any ideas?

1

There are 1 best solutions below

0
On

If the structure is fixed, you can manually encode it like:

func MarshalArray(in []Obj, out io.Writer) {
   io.WriteString(out,"[")
   for i,x:=range in {
       if i>0 {
         out.Write([]byte(","))
       }
       io.WriteString("\n  ")
       data,_:=json.Marshal(x)
       io.Write(data)
   }
   io.WriteString(out,"\n]")
}