Golang - Parsing JSON to struct Code Example

The code for Parsing JSON to struct

package main

import (
	"encoding/json"
	"fmt"
)

type Country struct {
	Name	 string
	Capital string
	Continent string
}

func main() {
	var countryObj Country
	// JSON data
	Data := []byte(`{
		"Name": "India",
		"Capital": "New Delhi",
		"Continent": "Asia"
	}`)

	// decoding countryObj struct
	// from json format
	err := json.Unmarshal(Data, &countryObj)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Struct Data is:", countryObj)
	fmt.Printf("Name: %s, Capital: %s, and Continent: %s.\n", countryObj.Name,
								countryObj.Capital, countryObj.Continent)
}


/*
Output:
Struct Data is: {India New Delhi Asia}
Name: India, Capital: New Delhi, and Continent: Asia.
*/
Code by IncludeHelp, on March 1, 2023 07:19

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.