0

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?

Flying onion
  • 126
  • 7
  • `encoding/json` can either indent, or not. A formatter that would understand why you arbitrarily want some lines formatted and others not would be far more complex than what's needed in the stdlib, or likely any third-party library. You'd have to write your own if it's important to your use case. – Adrian Aug 11 '21 at 13:24

1 Answers1

0

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]")
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59