M
M
Master Ruby2021-05-20 19:01:17
go
Master Ruby, 2021-05-20 19:01:17

How to structure a JSON object?

In python, there is pprint which outputs well-structured JSON.
I'm trying to get the same thing in Golang, but it doesn't work, it's been the second day, help)

func main() {
  artist := "Madonna"
  token := "5936fb55e90cdd9938f8e7086c783c40"
  url := fmt.Sprintf(
    "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=%s&api_key=%s&format=json", artist, token)
  res, err := http.Get(url)
  if err != nil {
    log.Fatal(err)
  }
  defer res.Body.Close()

  body, _ := ioutil.ReadAll(res.Body)
  data, err := json.MarshalIndent(string(body), "", "\t")

  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(string(data))
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Demin, 2021-05-20
@Dunaevlad

You can use Indent

package main

import (
  "bytes"
  "encoding/json"
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
)

func main() {
  artist := "Madonna"
  token := "5936fb55e90cdd9938f8e7086c783c40"
  url := fmt.Sprintf(
    "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=%s&api_key=%s&format=json", artist, token)
  res, err := http.Get(url)
  if err != nil {
    log.Fatal(err)
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    log.Fatal(err)
  }

  var pretty bytes.Buffer
  err = json.Indent(&pretty, body, "", "\t")
  if err != nil {
    log.Fatal(err)
  }
  fmt.Printf("%v\n", string(pretty.Bytes()))
}

V
Vladimir Korotenko, 2021-05-20
@firedragon

Replace tabs with 2 or 4 spaces

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question