Home »
Code Examples »
Golang Code Examples
Golang - How to Use Field Tags in the Definition of Struct Type Code Example
The code for How to Use Field Tags in the Definition of Struct Type
package main
import
(
"encoding/json"
"fmt"
)
type BookDetails struct
{
BookName string `json:"name"`
BookAuthor string `json: "author"`
BookPrice int `json: "price"`
}
func main() {
var b BookDetails
b.BookName = "The Power of your subconscious mind"
b.BookAuthor = "Joseph Murphy"
b.BookPrice = 150
fmt.Println(b)
// returns []byte which is b in JSON form.
jsonStr, err := json.Marshal(b)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(string(jsonStr))
}
/*
Output:
The Power of your subconscious mind Joseph Murphy 150}
{"name":"The Power of your subconscious mind","BookAuthor":"Joseph Murphy","BookPrice":150}
*/
Code by IncludeHelp,
on March 1, 2023 07:25