golang json
Go (or Golang) is a programming language that includes built-in support for encoding and decoding JSON data. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
To work with JSON in Go, you can use the built-in encoding/json package. This package provides functions for encoding Go data structures into JSON, and for decoding JSON data into Go data structures.
Here's an example of encoding a Go structure into JSON:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{Name: "Alice", Age: 30}
b, err := json.Marshal(p)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(b))
}
In this example, we define a Person structure with Name and Age fields. We then create a Person instance and use the json.Marshal function to encode it into a JSON byte slice. We print the resulting JSON string to the console.
The output of this program will be:
{"name":"Alice","age":30}
To decode JSON data into a Go data structure, you can use the json.Unmarshal function. Here's an example:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonStr := `{"name":"Alice","age":30}`
var p Person
err := json.Unmarshal([]byte(jsonStr), &p)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(p.Name, p.Age)
}
In this example, we define a Person structure and create a JSON string that represents a Person instance. We then use the json.Unmarshal function to decode the JSON string into a Person instance. We print the Name and Age fields to the console.
The output of this program will be:
Alice 30
``
原文地址: https://www.cveoy.top/t/topic/dn9f 著作权归作者所有。请勿转载和采集!