Answers for "golang parse json request body"

Go
1

golang read response body

//import package
import "io/ioutil"

//code snippet
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    
 //---------- optioninal ---------------------
    //handling Errors
    if err != nil {
        log.Fatal(err)
    }
    
    //print result
    bodyString := string(bodyBytes)
    log.Info(bodyString)
Posted by: Guest on January-24-2021
0

parsing json data object in golang example

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	//Simple Employee JSON object which we will parse
	empJson := `{
		"id": 11,
		"name": "Irshad",
		"department": "IT",
		"designation": "Product Manager",
		"address": {
			"city": "Mumbai",
			"state": "Maharashtra",
			"country": "India"
		}
	}`

	// Declared an empty interface
	var result map[string]interface{}

	// Unmarshal or Decode the JSON to the interface.
	json.Unmarshal([]byte(empJson), &result)

	address := result["address"].(map[string]interface{})

	//Reading each value by its key
	fmt.Println("Id :", result["id"],
		"nName :", result["name"],
		"nDepartment :", result["department"],
		"nDesignation :", result["designation"],
		"nAddress :", address["city"], address["state"], address["country"])
}
Posted by: Guest on April-17-2021

Browse Popular Code Answers by Language