skip to Main Content

I want to format my JSON to Golang unmarshelled output.I can’t see a thing there.

// Create an HTTP client with the API key.
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
    log.Fatal("Error creating request:", err)
}
req.Header.Add("Authorization", "Bearer "+apiKey)

// Make the HTTP request to fetch JSON data.
resp, err := client.Do(req)
if err != nil {
    log.Fatal("Error making HTTP request:", err)
}
defer resp.Body.Close()

// Read the JSON response into a byte slice.
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal("Error reading JSON data:", err)
}

// Unmarshal the JSON data into a map.
var target map[string]interface{}
err = json.Unmarshal(data, &target)
if err != nil {
    log.Fatalf("Unable to unmarshal JSON due to %s", err)
}

i done this and got,

map[droplets:[map[backup_ids:[1.4132617e+08 1.41783892e+08 1.42227987e+08 1.42667107e+08 1.43107709e+08] created_at:2020-06-04T17:40:05Z disk:50 features:[backups monitoring private_networking ipv6] id:1.94861944e+08 image:map[created_at:2020-05-15T05:47:50Z description:Ubuntu 20.04 x86 distribution:Ubuntu id:6.366398e+07 min_disk_size:20 name:20.04 (LTS) x64 public:false regions:[] size_gigabytes:2.36 slug: status:retired tags:[] type:base] kernel: locked:false memory:4096 name:staging-02 networks:map[v4:[map[gateway:10.104.0.1 ip_address:10.104.0.2 netmask:255.255.240.0 type:private] map[gateway:128.199.64.1 ip_address:128.199.111.88 netmask:255.255.192.0 type:public]] v6:[map[gateway:2400:6180:0:d0::1 ip_address:2400:6180:0:d0::e6d:6001 netmask:64 type:public]]] next_backup_window:map[end:2023-11-02T20:00:00Z start:2023-11-02T16:00:00Z] region:map[available:true features:[backups ipv6 metadata install_agent storage image_transfer] name:Singapore 1 sizes:[s-1vcpu-512mb-10gb s-1vcpu-1gb s-1vcpu-1gb-amd s-1vcpu-1gb-intel s-1vcpu-1gb-35gb-intel s-1vcpu-2gb s-1vcpu-2gb-amd s-1vcpu-2gb-intel s-1vcpu-2gb-70gb-intel s-2vcpu-2gb s-2vcpu-2gb-amd s-2vcpu-2gb-intel s-2vcpu-2gb-90gb-intel s-2vcpu-4gb s-2vcpu-4gb-amd s-2vcpu-4gb-intel s-2vcpu-4gb-120gb-intel c-2 c2-2vcpu-4gb s-4vcpu-8gb s-4vcpu-8gb-amd s-4vcpu-8gb-intel g-2vcpu-8gb s-4vcpu-8gb-240gb-intel gd-2vcpu-8gb m-2vcpu-16gb c-4 c2-4vcpu-8gb s-8vcpu-16gb m3-2vcpu-16gb s-8vcpu-16gb-amd s-8vcpu-16gb-intel g-4vcpu-16gb s-8vcpu-16gb-480gb-intel so-2vcpu-16gb m6-2vcpu-16gb gd-4vcpu-16gb so1_5-2vcpu-16gb m-4vcpu-32gb c-8 c2-8vcpu-16gb m3-4vcpu-32gb g-8vcpu-32gb so-4vcpu-32gb m6-4vc………

i want this to be more formatted how to do it.I want to extract the variables inside this and then do some calculations but this seems a mess .I cant work with this how to format it?

// Create an HTTP client with the API key.
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
    log.Fatal("Error creating request:", err)
}
req.Header.Add("Authorization", "Bearer "+apiKey)

// Make the HTTP request to fetch JSON data.
resp, err := client.Do(req)
if err != nil {
    log.Fatal("Error making HTTP request:", err)
}
defer resp.Body.Close()

// Read the JSON response into a byte slice.
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal("Error reading JSON data:", err)
}

// Unmarshal the JSON data into a map.
var target map[string]interface{}
err = json.Unmarshal(data, &target)
if err != nil {
    log.Fatalf("Unable to unmarshal JSON due to %s", err)
}

i done this and got,

map[droplets:[map[backup_ids:[1.4132617e+08 1.41783892e+08 1.42227987e+08 1.42667107e+08 1.43107709e+08] created_at:2020-06-04T17:40:05Z disk:50 features:[backups monitoring private_networking ipv6] id:1.94861944e+08 image:map[created_at:2020-05-15T05:47:50Z description:Ubuntu 20.04 x86 distribution:Ubuntu id:6.366398e+07 min_disk_size:20 name:20.04 (LTS) x64 public:false regions:[] size_gigabytes:2.36 slug: status:retired tags:[] type:base] kernel: locked:false memory:4096 name:staging-02 networks:map[v4:[map[gateway:10.104.0.1 ip_address:10.104.0.2 netmask:255.255.240.0 type:private] map[gateway:128.199.64.1 ip_address:128.199.111.88 netmask:255.255.192.0 type:public]] v6:[map[gateway:2400:6180:0:d0::1 ip_address:2400:6180:0:d0::e6d:6001 netmask:64 type:public]]] next_backup_window:map[end:2023-11-02T20:00:00Z start:2023-11-02T16:00:00Z] region:map[available:true features:[backups ipv6 metadata install_agent storage image_transfer] name:Singapore 1 sizes:[s-1vcpu-512mb-10gb s-1vcpu-1gb s-1vcpu-1gb-amd s-1vcpu-1gb-intel s-1vcpu-1gb-35gb-intel s-1vcpu-2gb s-1vcpu-2gb-amd s-1vcpu-2gb-intel s-1vcpu-2gb-70gb-intel s-2vcpu-2gb s-2vcpu-2gb-amd s-2vcpu-2gb-intel s-2vcpu-2gb-90gb-intel s-2vcpu-4gb s-2vcpu-4gb-amd s-2vcpu-4gb-intel s-2vcpu-4gb-120gb-intel c-2 c2-2vcpu-4gb s-4vcpu-8gb s-4vcpu-8gb-amd s-4vcpu-8gb-intel g-2vcpu-8gb s-4vcpu-8gb-240gb-intel gd-2vcpu-8gb m-2vcpu-16gb c-4 c2-4vcpu-8gb s-8vcpu-16gb m3-2vcpu-16gb s-8vcpu-16gb-amd s-8vcpu-16gb-intel g-4vcpu-16gb s-8vcpu-16gb-480gb-intel so-2vcpu-16gb m6-2vcpu-16gb gd-4vcpu-16gb so1_5-2vcpu-16gb m-4vcpu-32gb c-8 c2-8vcpu-16gb m3-4vcpu-32gb g-8vcpu-32gb so-4vcpu-32gb m6-4vc………

i want this to be more formatted how to do it.I want to extract the variables inside this and then do some calculations but this seems a mess .I cant work with this how to format it?

2

Answers


  1. To make the JSON data more readable and structured, you can use the json.MarshalIndent function to marshal the data back into a formatted JSON string. Here’s how you can do it:

    // Create an HTTP client with the API key.
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal("Error creating request:", err)
    }
    req.Header.Add("Authorization", "Bearer "+apiKey)
    
    // Make the HTTP request to fetch JSON data.
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal("Error making HTTP request:", err)
    }
    defer resp.Body.Close()
    
    // Read the JSON response into a byte slice.
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal("Error reading JSON data:", err)
    }
    
    // Unmarshal the JSON data into a map.
    var target map[string]interface{}
    err = json.Unmarshal(data, &target)
    if err != nil {
        log.Fatalf("Unable to unmarshal JSON due to %s", err)
    }
    
    // Marshal the map back into a formatted JSON string.
    formattedJSON, err := json.MarshalIndent(target, "", "  ")
    if err != nil {
        log.Fatal("Error formatting JSON:", err)
    }
    
    // Now you have the formatted JSON in the 'formattedJSON' variable.
    fmt.Println(string(formattedJSON))
    
    Login or Signup to reply.
  2. You can write a utility function that can beautifully print any given struct/map/slice:

    func JSONStringify(obj interface{}) {
        beautifulJsonByte, err := json.MarshalIndent(obj, "", "  ")
        body := ""
        if err != nil {
            body = fmt.Sprintf("%v", obj)
        } else {
            body = string(beautifulJsonByte)
        }
        
        fmt.Println(string(beautifulJsonByte))
    }
    

    Usage:

    var target map[string]interface{}
    
    err = json.Unmarshal(data, &target)
    if err != nil {
        log.Fatalf("Unable to unmarshal JSON due to %s", err)
    }
    
    JSONStringify(target)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search