How to format and print data as JSON or XML using fmt in Go?

To format and print data as JSON or XML using fmt in Go, you can follow these steps:

  1. Import the required packages:
import ( "encoding/json" "encoding/xml" "fmt" )
  1. Define a struct that represents your data. This struct will be used for both JSON and XML encoding:
type Data struct { Field1 string `json:"field1" xml:"field1"` Field2 int `json:"field2" xml:"field2"` // ... other fields }
  1. Create an instance of the Data struct with the desired values:
data := Data{ Field1: "value1", Field2: 123, // ... set other fields }
  1. To print the data as JSON, use json.Marshal to encode the struct to JSON format and then fmt.Println to print it:
jsonData, err := json.Marshal(data) if err != nil { fmt.Println("Error encoding JSON:", err) return } fmt.Println(string(jsonData))
  1. To print the data as XML, use xml.Marshal to encode the struct to XML format and then fmt.Println to print it:
xmlData, err := xml.Marshal(data) if err != nil { fmt.Println("Error encoding XML:", err) return } fmt.Println(string(xmlData))

That's it! You have formatted and printed the data as JSON or XML using fmt in Go. Make sure to handle any potential errors that may occur during encoding.