How to parse JSON data in Golang?

WBOY
Release: 2024-06-03 15:33:09
Original
482 people have browsed it

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"
)
Copy after login

2. Read JSON data from file

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

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
}
Copy after login

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"])
Copy after login

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)
}
Copy after login

Save the following JSON data to the file:

{
  "Name": "John Doe",
  "Age": 30
}
Copy after login

Then run the program, the output is as follows:

Name: John Doe, Age: 30
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!