Home > Article > Backend Development > How to parse JSON data in Golang?
Parsing JSON data in Golang involves four main steps: Import the आवश्यक package, which includes json, fmt and ioutil. Read JSON data from a file. Decode JSON data into a structure or map. Access key-value pairs in a map or use a decoded struct.
Golang provides powerful tools to process JSON data, which can be achieved through the following steps:
import ( "encoding/json" "fmt" "io/ioutil" )
jsonFile, err := ioutil.ReadFile("data.json") if err != nil { fmt.Println("Error reading JSON file:", err) return }
Decoding To the structure:
type Person struct { Name string Age int } var person Person err = json.Unmarshal(jsonFile, &person) if err != nil { fmt.Println("Error decoding JSON data:", err) return }
Decode into the map:
var data map[string]interface{} err = json.Unmarshal(jsonFile, &data) if err != nil { fmt.Println("Error decoding JSON data:", err) return } // 访问 map中的键值对 fmt.Println("Name:", data["Name"])
Read the JSON file and print the name and age:
package main import ( "encoding/json" "fmt" "io/ioutil" ) type Person struct { Name string Age int } func main() { jsonFile, err := ioutil.ReadFile("data.json") if err != nil { fmt.Println("Error reading JSON file:", err) return } var person Person err = json.Unmarshal(jsonFile, &person) if err != nil { fmt.Println("Error decoding JSON data:", err) return } fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age) }
Save the following JSON data to the file:
{ "Name": "John Doe", "Age": 30 }
Then run the program, the output is as follows:
Name: John Doe, Age: 30
The above is the detailed content of How to parse JSON data in Golang?. For more information, please follow other related articles on the PHP Chinese website!