To format and print data as JSON or XML using fmt
in Go, you can follow these steps:
import (
"encoding/json"
"encoding/xml"
"fmt"
)
type Data struct {
Field1 string `json:"field1" xml:"field1"`
Field2 int `json:"field2" xml:"field2"`
// ... other fields
}
Data
struct with the desired values:data := Data{
Field1: "value1",
Field2: 123,
// ... set other fields
}
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))
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.