Home >Backend Development >Golang >How to convert JSON data to structure in Golang?

How to convert JSON data to structure in Golang?

王林
王林Original
2024-06-05 20:47:00688browse

In Golang, JSON data can be converted into a structure through the following steps: define a structure with field names that match the JSON attribute names, and use the json tag to specify the JSON field names. Use the json.Unmarshal function from the encoding/json package to parse a JSON string and convert it into a pointer to a structure. Check for parsing errors. Access structure fields to extract data.

如何在 Golang 中将 JSON 数据转换为结构体?

How to convert JSON data into a structure in Golang

Introduction

Golang provides the encoding/json package to easily process JSON data. It allows you to convert JSON data into structures, making it easy to access and manipulate JSON data.

Practical case

Suppose you have a JSON string:

{
  "name": "John Doe",
  "age": 30,
  "occupation": "Software Engineer"
}

and want to convert it into a structure. Here are the steps:

  1. Define the structure:
type Person struct {
  Name       string `json:"name"`
  Age        int    `json:"age"`
  Occupation string `json:"occupation"`
}
  • struct keyword creates a new Structure type.
  • Field names match JSON property names.
  • json tag specifies the JSON field name.
  1. Parse JSON data:
import "encoding/json"

var jsonStr = `{
  "name": "John Doe",
  "age": 30,
  "occupation": "Software Engineer"
}`

var person Person

err := json.Unmarshal([]byte(jsonStr), &person)
if err != nil {
  // 处理错误
}
  • json.Unmarshal The function parses the JSON string and Convert it to a pointer to a structure.
  • jsonStr is a JSON string.
  • person is the target structure.
  • If there is an error, Unmarshal will return that error.
  1. Accessing structure fields:
fmt.Println(person.Name)  // "John Doe"
fmt.Println(person.Age)   // 30
fmt.Println(person.Occupation)  // "Software Engineer"
  • Once the JSON data is parsed correctly, you can access it just like any other Structure fields are accessed just like structure members.

Note

  • Make sure that the type of the structure field is compatible with the value type in the JSON attribute.
  • JSON property names must match structure field names unless you use the json tag.
  • If the JSON data cannot be parsed, check for errors in Unmarshal.

The above is the detailed content of How to convert JSON data to 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