Home  >  Article  >  Backend Development  >  How to parse JSON data in Golang?

How to parse JSON data in Golang?

WBOY
WBOYOriginal
2024-06-03 15:33:09483browse

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 中解析 JSON 数据?

How to parse JSON data in Golang

Golang provides powerful tools to process JSON data, which can be achieved through the following steps:

1. Import necessary packages

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

2. Read JSON data from file

jsonFile, err := ioutil.ReadFile("data.json")
if err != nil {
    fmt.Println("Error reading JSON file:", err)
    return
}

3. Decode JSON data into structure or map

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"])

Practical case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn