Home >Backend Development >Golang >How to Unmarshal JSON with Unknown Field Names in Go?

How to Unmarshal JSON with Unknown Field Names in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 11:28:15407browse

How to Unmarshal JSON with Unknown Field Names in Go?

Unmarshal JSON with Unknown Fieldnames into a Struct

Problem:

Unmarshalling JSON data with unknown fieldnames can be challenging when the structure of the JSON response is consistent but the specific fieldnames vary.

Solution:

Utilizing a map as the key-value store allows for handling instances with unknown fieldnames. The value of the map should be a struct that represents the common structure of the JSON data.

Example:

Assume the following JSON structure:

{
    "unknown_field": {
        "known_field_1": [[1,2,3,4,5],[10,20,30,40,50],[100,200,300,400,500]],
        "known_field_2": [[11,21,31,41,51]],
        "known_field_3": [[12,22,32,42,52],[14,44,34,44,54]]
    }
}

The corresponding Go struct:

type mData struct {
    KnownField1 [][5]int `json:"known_field_1"`
    KnownField2 [][5]int `json:"known_field_2"`
    KnownField3 [][5]int `json:"known_field_3"`
}

Unmarshaling Code:

var data map[string]mData

if err := json.Unmarshal(body, &data); err != nil {
    panic(err)
}

fmt.Println(data)
for k, v := range data {
    fmt.Println(k, v)
}

Output:

map[unknown_field:{[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}]
unknown_field {[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}

By leveraging a map, the code effectively handles the unknown fieldnames while still accurately extracting the data into the known struct fields.

The above is the detailed content of How to Unmarshal JSON with Unknown Field Names 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