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

How to Unmarshal JSON Data with Unknown or Variable Keys in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 03:44:09271browse

How to Unmarshal JSON Data with Unknown or Variable Keys in Go?

Unmarshal JSON Data of Unknown Format with Variable Keys

When dealing with JSON data that has unknown or variable keys, it can be challenging to define a specific GoLang struct for unmarshalling purposes. This article addresses this problem by providing two viable solutions.

Solution 1: Using map[string]interface{}

If you do not have any knowledge about the keys present in the JSON payload, you can utilize a map with a string key and an interface{} value (i.e., map[string]interface{}). This approach allows for dynamic unmarshalling of the data without requiring a predefined struct. For example:

var grades map[string]interface{}

err := json.Unmarshal([]byte(jsonString), &grades)
fmt.Println(err)
fmt.Printf("%#v\n", grades)

Solution 2: Using a Struct with Ignored Fields

If you still wish to use a struct but want to ignore unknown fields during unmarshalling, you can use the json:"-" tag for those fields. This tag instructs the JSON decoder to not consider these fields during the process. For instance:

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

err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
fmt.Println(err)
fmt.Printf("%#v\n", gradesData)

Both solutions offer flexibility in handling JSON data with unknown or variable keys. However, for further processing or data manipulation, you may need to cast the data to specific types depending on your requirements.

The above is the detailed content of How to Unmarshal JSON Data with Unknown or Variable Keys in Go?. 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