Home > Backend Development > Golang > How to Unmarshal JSON with Unexpected Field Names into a Go Struct?

How to Unmarshal JSON with Unexpected Field Names into a Go Struct?

Mary-Kate Olsen
Release: 2024-12-24 12:29:18
Original
751 people have browsed it

How to Unmarshal JSON with Unexpected Field Names into a Go Struct?

Unmarshaling JSON with Unknown Fieldnames to Struct

Question:

Is it possible to unmarshal JSON with fieldnames that are unknown in advance, while maintaining the given structure?

Problem:

Consider a JSON response where unknown fieldnames wrap a common structure. This structure must be mapped to a struct, but the fieldnames vary.

{
    "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]]
        }
}
Copy after login

Answer:

Yes, it is possible to unmarshal such JSON using a map as the root struct element, where keys are the unknown fieldnames and values are instances of the known 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"`
}
Copy after login
var data map[string]mData
if err := json.Unmarshal(body, &data); err != nil {
    panic(err)
}
Copy after login

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]]}
Copy after login

The above is the detailed content of How to Unmarshal JSON with Unexpected Field Names into a Go Struct?. 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