Home > Backend Development > Golang > How to Unmarshal JSON Data with Unknown Keys and Values in Go?

How to Unmarshal JSON Data with Unknown Keys and Values in Go?

Patricia Arquette
Release: 2024-12-01 09:34:11
Original
713 people have browsed it

How to Unmarshal JSON Data with Unknown Keys and Values in Go?

Unmarshaling JSON Data of Unknown Format

When working with JSON payloads, it can be challenging to handle data with an unknown format. This situation arises when the keys and values within the JSON structure are not predefined. To address this, Go offers several approaches to unmarshaling unknown formats.

In the provided JSON data, the keys represent subjects, and the values are arrays of student grades. To unmarshal this data effectively, we can utilize the following techniques:

Option 1: Using map[string]interface{}

If the keys are entirely unknown, you can employ a map[string]interface{} to unmarshal the JSON payload. This method creates a map where the keys are strings, and the values are interfaces representing the unmarshaled data.

var grades map[string]interface{}

err := json.Unmarshal([]byte(jsonString), &grades)
Copy after login

Option 2: Using a Custom Struct

If you have a specific structure you want to represent the data, you can create a custom struct and ignore the unknown keys during unmarshaling using the json:"-" tag. The Grades field in the GradeData struct will contain the unmarshaled data as a map[string]interface{}.

type GradeData struct {
    Grades map[string]interface{} `json:"-"`
}

gradesData := GradeData{}
err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
Copy after login

By utilizing either of these approaches, you can effectively unmarshal JSON data of unknown format and access the data in Go. It is important to choose the method that best aligns with the requirements of your application.

The above is the detailed content of How to Unmarshal JSON Data with Unknown Keys and Values in Go?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template