Morales
Morales

Reputation: 138

Pretty JSON retrieved from response in GoLang

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.

Upvotes: 4

Views: 8423

Answers (1)

icza
icza

Reputation: 417412

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?

Upvotes: 13

Related Questions