JSON handling in Go

 JSON handling in Go


Go has built-in support for encoding and decoding JSON data.


The encoding/json package provides functions for encoding Go values into JSON and decoding JSON into Go values.



type Person struct {

    Name string `json:"name"`

    Age  int    `json:"age"`

}


p := Person{Name: "John Doe", Age: 42}

data, err := json.Marshal(p)

if err != nil {

    // handle the error

}

fmt.Println(string(data)) // prints {"name":"John Doe","age":42}


var q Person

err = json.Unmarshal(data, &q)

if err != nil {

    // handle the error

}

fmt.Println(q.Name, q.Age) // prints John Doe 42

In this example, we define a Person struct with two fields: Name and Age. We then create a new Person value and encode it into JSON by using the json.Marshal() function.


We also decode the JSON data back into a Person value by using the json.Unmarshal() function.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...