Go language processing JSON data encoding and decoding method _golang_script home

A method of encoding and decoding JSON data in the Go language

Updated: Apr 30, 2024 11:28:00 Author: Yards on the Nuggets
In the Go language, the encoding and decoding of JSON data mainly rely on the encoding/json package in the standard library, which provides two core functions: Marshal and Unmarshal. This article introduces the method of encoding and decoding of JSON data in the Go language, and the friends who need it can refer to it

introduction

In the Go language, the encoding and decoding of JSON data is mainly dependent on the encoding/json package in the standard library. This package provides two core functions: Marshal for encoding data structures in Go into JSON-formatted byte slices, and Unmarshal for decoding JSON-formatted byte slices into Go data structures.

reason

In Web development or API interaction, JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy for humans to read and write, but also easy for machines to parse and generate. Therefore, encoding and decoding JSON data in the Go language is a common requirement in scenarios such as processing HTTP requests and responses, storing and transferring data, and so on.

solution

Encoded JSON data

In Go, you can use the json.Marshal function to encode the Go data structure into JSON-formatted byte slices. For example:

package main import ( "encoding/json" "fmt" "log" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() {p := Person{Name: "Alice", Age: 30} // Encoded as json jsonData, err := json.Marshal(p) if err! = nil {log.Fatalf("JSON encoding failed: %s", err)} fmt.Println(string(jsonData)) // Output: {"name":"Alice","age":30}}

In the example above, we defined a Person struct and used the json:"name" and json:"age" tags to specify the JSON field name. We then created a Person instance and used the json.Marshal function to encode it into JSON-formatted byte slices.

Decode JSON data

To decode JSON data into Go data structures using the json.unmarshal function, you need to first parse the JSON data into byte slices and then call the Unmarshal function. For example:

package main import ( "encoding/json" "fmt" "log" ) type Person struct { Name string `json:"name"` Age int `json:"age"` } func main() { jsonStr := `{"name":"Bob", "age":25} '// Convert json strings to byte slices jsonData := []byte(jsonStr) var p Person // Decode JSON err := json.Unmarshal(jsonData, &p) if err ! = nil {log.Fatalf("JSON decoding failed: %s", err)} fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age) // Output: Name: Bob, Age: 25 }

In this example, we have a json string that we convert into a byte slice and decode into an instance of the Person struct using the json.unmarshal function. Note that the second argument passed to Unmarshal is a pointer to the data structure to be populated.

Sample code summary

The two examples above show how to use the encoding/json package to encode and decode JSON data, respectively. The encoding process converts the Go data structure into a JSON-formatted byte slice, while the decoding process converts the JSON-formatted byte slice back into the Go data structure. These two processes are useful in Web service development, data persistence, and so on.

Matters needing attention

  • Make sure that the field labels of your Go data structure match the key names in the JSON.
  • When decoding JSON, if the JSON contains fields that do not exist in the Go data structure, these fields are ignored. Conversely, if there are fields in the Go data structure that do not exist in JSON, those fields will retain their zero value.
  • If the JSON string is invalid or does not match the field type of the Go data structure,json.UnmarshalAn error will be returned.

By understanding and using the encoding/json package, you can easily handle the task of encoding and decoding JSON data in Go.

The above is the detailed content of the method of encoding and decoding JSON data in the Go language, more information about Go JSON encoding and decoding please pay attention to other related articles in the script home!

Related article

  • golang sql语句超时控制方案及原理

    golang sql statement timeout control scheme and principle

    General applications in the execution of a sql statement, will set a timeout time to this sql, this article mainly introduces the golang sql statement timeout control scheme and principle, has a certain reference value, interested can understand
    2023-12-12
  • 深入探讨Golang中如何进行并发发送HTTP请求

    How to send HTTP requests concurrently in Golang

    In the Golang world, sending HTTP requests concurrently is an important skill for optimizing Web applications, and this article explores various ways to achieve this goal. I hope the sample code in this article will be helpful
    2024-01-01
  • Go经典面试题汇总(填空+判断)

    Go Classic Interview Questions Summary (Fill in the blanks + Judge)

    This article mainly introduces the Go classic interview question summary (fill in the blank + judgment), the content of this article is detailed, has a good reference value, I hope to help you, the need of friends can refer to
    2023-01-01
  • Go语言中乐观锁与悲观锁的具体使用

    Specific use of optimistic lock and pessimistic lock in Go language

    Optimistic lock and pessimistic lock are two kinds of ideas, used to solve the problem of data competition in concurrent scenarios, this paper mainly introduces the specific use of optimistic lock and pessimistic lock in Go language, has certain reference value, interested can understand
    2024-01-01
  • C语言的10大基础算法

    C language 10 basic algorithms

    Algorithm is the soul of a program and software, as an excellent programmer, only have a comprehensive grasp of some basic algorithms, will be in the process of designing programs and writing code appears handy. This article mainly introduces the 10 basic algorithms of the C language, and the friends who need them can refer to it
    2019-09-09
  • 详解如何在golang镜像中设置指定时区

    Details How to set the specified time zone in the golang image

    This article mainly introduces in detail how to set the specified time zone in the golang image, the example code in the article explains in detail, has a certain reference value, interested can understand
    2023-04-04
  • go按行读取文件的三种实现方式汇总

    go is a summary of three implementations that read files by line

    Recently have encountered the need to use go to read the file situation, the following article mainly introduces to you about go to read the file by line of three ways to achieve, the article through the example code is very detailed, the need of friends can refer to
    2022-09-09
  • golang实现并发控制的方法和技巧

    golang concurrency control methods and techniques

    golang is a programming language that supports concurrency and provides powerful features such as goroutine and channel that allow us to easily create and manage multiple execution units for efficient task processing, and in this article, we will introduce some golang The methods and techniques of concurrency control, hope to help you
    2024-03-03
  • Go常问的一些面试题汇总(附答案)

    Go frequently asked some interview questions summary (with answers)

    Usually we will have some good Golang interview questions, so to sum up, so that other Golang developers can also see, but also to test their own abilities and remind their shortcomings, this article mainly introduces you about Go frequently asked some interview questions and answers related information, need friends can refer to
    2023-10-10
  • 一文教你如何快速学会Go的struct数据类型

    How to quickly learn Go struct data type

    A structure is a user-defined type that represents a collection of fields. It can be used where data is grouped into a single unit rather than each data as a separate value. This article will talk about the use of struct data types in Go, and you can refer to it if you need it
    2023-03-03

Latest comments