6

I retrieve JSON as GET response from and endpoint

response, _ := http.Get("https://website-returning-json-value.com") data, _ := ioutil.ReadAll(response.Body) w.Write(data) 

It returns me a JSON value, which is OK, but it is very ugly (no indents etc.). I would like to make it pretty. I've read that there is util function like MarshalIndent which does the job, but this works for JSON object (?) and ReadAll function returns []byte, so it does not work. I read the documentation regarding encoding/json package but there's a lot of information and I got a little bit stuck/confused.

As far as I understand it should be done, I should get []byte via ReadAll function -> convert it to the JSON -> prettify it -> turn to []byte again.

1
  • 1
    There is no need to do that, unmarshal the json into structs and then marshal it if you want. Commented Oct 10, 2018 at 13:09

1 Answer 1

15

There is json.Indent() for this purpose. Example using it:

src := []byte(`{"foo":"bar","x":1}`) dst := &bytes.Buffer{} if err := json.Indent(dst, src, "", " "); err != nil { panic(err) } fmt.Println(dst.String()) 

Output (try it on the Go Playground):

{ "foo": "bar", "x": 1 } 

But indentation is just for human eyes, it carries the same information, and libraries don't need indented JSON.

Also see: Is there a jq wrapper for golang that can produce human readable JSON output?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, working as expected. I know it might be useless in most cases, but it is for demo purposes and I wanted to look it human readable ;) Thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.