17

After I do

 json, err := json.Marshal(buf) 

I get something like:

{"a":123,"b":"abc"} 

But what I want is an indented version of this:

{ "a": 123, "b": "abc" } 

How?

3
  • You want to see it formatted in chrome browser then use JSON Formatter extension. Commented Aug 27, 2017 at 7:59
  • 4
    use MarshalIndent Commented Aug 27, 2017 at 8:00
  • @Rakib no, just want to print it to console or save to file Commented Aug 27, 2017 at 8:00

1 Answer 1

31

Use json.MarshalIndent(group, "", "\t"), try this:

package main import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := json.MarshalIndent(group, "", "\t") if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) } 

output:

{ "ID": 1, "Name": "Reds", "Colors": [ "Crimson", "Red", "Ruby", "Maroon" ] } 
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any way to have lists of basic types not linebreaked?
@NikolaiEhrhardt: You may write Custom JSON Marshalling yourself.
yes, will become a lot of work =). I also assume it should be possible, with reflect and whatsoever.
@NikolaiEhrhardt: regexp: (\[[^[\]]+\]) Try this
I only want to format lists of basic types...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.