Home  >  Article  >  Backend Development  >  How to handle JSON data with nested structure in Golang?

How to handle JSON data with nested structure in Golang?

WBOY
WBOYOriginal
2024-06-02 12:41:57837browse

Processing nested structured JSON data in Go: Use the encoding/json package to encode and decode JSON data. Use the json.Unmarshal() function to decode JSON data into nested structures. Encode nested structures into JSON using the json.Marshal() function. Access nested data by accessing fields in the structure. Get and decode nested structured JSON data from the API.

如何在 Golang 中处理有嵌套结构的 JSON 数据?

How to process JSON data with nested structures in Go

In Go, you can use encoding The /json package makes it easy to handle nested structures of JSON data. This package provides powerful functions for encoding and decoding JSON data.

Encoding and Decoding Nested Structures

To encode or decode nested structures, you can use json.Unmarshal() and json.Marshal() Function.

// 嵌套结构的 JSON 数据
jsonStr := `{"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "New York"}}`

// 解码 JSON 数据到嵌套结构
type Person struct {
    Name string
    Age  int
    Address Address
}

var person Person
err := json.Unmarshal([]byte(jsonStr), &person)
if err != nil {
    // 处理错误
}

// 访问嵌套字段
fmt.Println(person.Name) // John Doe
fmt.Println(person.Address.Street) // 123 Main St

// 编码嵌套结构为 JSON
jsonBytes, err := json.Marshal(person)
if err != nil {
    // 处理错误
}

// 输出 JSON 数据
fmt.Println(string(jsonBytes))

Practical Case: Getting Data from API

Now, let us see a practical case where we will get JSON data containing nested structure from API and It decodes into a Go structure.

package main

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

type Post struct {
    ID          int

The above is the detailed content of How to handle JSON data with nested structure 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