3

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.

Morales
  • 128
  • 2
  • 11

1 Answers1

11

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • 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! – Morales Oct 10 '18 at 13:35